首页 > 解决方案 > 如果使用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();

}

标签: phpeloquentlaravel-5.8laravel-query-builder

解决方案


您必须在查询中添加条件。但是请检查下面的代码,这将为您的代码添加更多漂亮的外观。

$loans = Loan::select('date_release')->where('invalid',false)->where('transaction_year', $transyear);
if(!empty($loantype)){
  $loans = $loans->where('loan_type', $loantype); 
}   
$result = $loans->get();

推荐阅读