【问题标题】:How to return all records in a column if where clause parameter is null using laravel?如果使用laravel的where子句参数为null,如何返回列中的所有记录?
【发布时间】:2021-11-29 02:57:22
【问题描述】:
$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();

}

【问题讨论】:

    标签: php eloquent laravel-5.8 laravel-query-builder


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2017-10-26
      • 1970-01-01
      相关资源
      最近更新 更多