首页 > 解决方案 > laravel 查询中的 if 条件

问题描述

有时有些变量为空,所以如何检查变量不为空并直接应用于查询

 $fiter_products = DB::table('products')->DISTINCT('modalid')->DISTINCT('brandid')->select('rimdiameter','modalid','modalname1','modalname2','image1','brand','minprice','maxprice')->where('hubbore','>=',$centre_bore)->where('boltpattern',$boltptn)->where('rimdiameter', $diameter)->where('rimwidth', $width)->where('rimwidthfront', $frontwid)->where('construction', $construct)->where('modalname2', $color)->where('brand', $brand)->get(); 

有什么办法可以解决这个问题?

标签: laravelif-statement

解决方案


您可以将另一个闭包作为第三个参数传递给when 方法。如果第一个参数评估为 false,则此闭包将执行。

$fiter_products = DB::table('products')
                   ->DISTINCT('modalid')
                   ->DISTINCT('brandid')
                   ->select('rimdiameter','modalid','modalname1','modalname2','image1','brand','minprice','maxprice')
->when($centre_bore, function($query,  $centre_bore) {
    $query->where('hubbore','>=',$centre_bore);
})->when($boltptn, function($query, $boltptn) {
    $query->where('boltpattern',$boltptn);
})...

推荐阅读