php - 如果使用laravel的where子句参数为null,如何返回列中的所有记录?
问题描述
$loantype = $request['regloan_type'];
$loans = Loan::select('date_release')
->where('invalid',false)
->where('transaction_year', $transyear)
->where('loan_type', $loantype)
->get();
如果变量$loantype
返回 null 那么我想选择该列中的所有记录。如何在 laravel where 子句中做到这一点?
我已经习惯if else statement
了得到我想要的。但是有没有办法不使用就可以做到这一点if else statement
?
代码:
$loantype = (empty($request['regloan_type'])) ? null : $request['regloan_type'];
if($loantype==null){
$loans = Loan::select('date_release')
->where('invalid',false)
->where('transaction_year', $transyear)
->get();
}else{
$loans = Loan::select('date_release')
->where('invalid',false)
->where('transaction_year', $transyear)
->where('loan_type', $loantype)
->get();
}
解决方案
您必须在查询中添加条件。但是请检查下面的代码,这将为您的代码添加更多漂亮的外观。
$loans = Loan::select('date_release')->where('invalid',false)->where('transaction_year', $transyear);
if(!empty($loantype)){
$loans = $loans->where('loan_type', $loantype);
}
$result = $loans->get();
推荐阅读
- regex - 正则表达式匹配多个条目
- java - 如何仅反转字符串中的数字
- firebase - 为什么当我的 TextFormField 获得焦点时我的页面会重新加载?
- mqtt - Twincat 3 中与 Microsoft Azure 云的 MQTT 连接
- flutter - 如何在 Flutter 中将音频与 lottie / rive 动画同步?
- php - laravel 队列中的 ShouldBeUnique 是什么
- pine-script - 当有 2 支蜡烛但少于 4 支时如何突出显示?
- html - ngxPrint 在内部组件的角度使用时无效
- python - 如何通过按单元格删除重复项将数字数据框的 ColA 转换为按每个单元格值排序?
- java - Java比较器问题(比较两次)