2017-08-05 72 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();