Laravel - where子句中的多个值

时间:2017-08-05 06:16:08

标签: laravel

我需要使用laravel 5.4进行搜索。我有下一个要搜索的字段

我想搜索这7个字段。我使用这个查询:

if ($categoryIn <> ''  AND 
    $brandIn == ' '    AND 
    $model == ' '      AND 
    $fuelIn == ''      AND 
    $priceMinIn == '0' AND 
    $priceMaxIn == '0' AND 
    $kmm == '0') {
    $cars = Cars_models::Where('Categorie', 'LIKE',  $categoryIn )->get ();
}
else if ($categoryIn <> ''     AND 
            $brandIn <> ' '    AND 
            $model == ' '      AND 
            $fuelIn == ''      AND 
            $priceMinIn == '0' AND 
            $priceMaxIn == '0' AND 
            $kmm == '0') {
    $cars = Cars_models::Where('Categorie','LIKE',$categoryIn)
            ->Where('Brand', 'LIKE',  $brandIn)
            ->get ();
} else if...

但我需要很多组合。任何人都可以帮我看一个更简单的方法吗?因为如果我这样写每个组合都无法处理它。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。最简单的是:

$q = Cars_models::query();
if ($categoryIn) { $q->where("categorie","LIKE",$categoryIn); }
if ($brandIn) { $q->where("Brand","LIKE", $brandIn); }   
if ($model) { $q->where("model","LIKE",$model); } 
... 
$cars = $q->get();

或者你可以这样做:

$conditions = collect([ 
          [ "categorie", "LIKE", $categoryIN ], 
          [ "Brand", "LIKE" , $brandIn ],
          ...
          ])->filter(function ($value) { return !empty($value[2]); }); //Remove all conditions with an empty second part

$cars = Cars_models::where($conditions->all())->get();