2017-08-05 2 views
2

Ich muss mit Laravel 5.4 suchen. Ich habe folgende Felder zu suchenLaravel - mehrfacher Wert in Where-Klausel

Ich möchte diese 7 Felder suchen. Ich benutze diese Abfrage:

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... 

Aber ich habe zu viele Kombinationen. Kann mir jemand helfen, mir einen einfacheren Weg zu zeigen? Weil ich nicht damit umgehen kann, wenn ich so jede Kombination schreibe.

Irgendeine Idee?

+2

Sehen Sie hier das wird Ihnen helfen https://stackoverflow.com/questions/45511015/writing-a-function-in-laravel –

+0

Großartig, du hast eine Lösung –

Antwort

0

Es gibt viele Möglichkeiten, dies zu tun. Die einfachste ist:

$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 Sie tun können:

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