2017-08-05 143 views
2

我需要使用laravel进行搜索5.4。我有下一个搜索字段Laravel - 在where子句中的多个值

我想搜索这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... 

但我有很多组合。任何人都可以帮我展示一个更简单的方法吗?因为我不能处理它,如果我写这样的每一个组合。

有什么想法?

+2

看到这里,这将帮助你https://stackoverflow.com/questions/45511015/writing-a-function-in-laravel –

+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(); 

Alternatevely你可以这样做:

$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();