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