Laravel advanced search query fix

后端 未结 8 1459
终归单人心
终归单人心 2021-01-28 21:34

I have a search form with multiple input and select boxes I need help to get if conditions in my query in order to each part works separately and all at once.

he

8条回答
  •  死守一世寂寞
    2021-01-28 22:01

    You can use laravel orWhere and orWhereHas to get results separately and all at once, let's say you do not select min_price and max_price but you have selected brand then all products with this brnad should be return, your query will look like this

    $products = Product::orWhere('price','>=',$min_price)
    ->orWhere('price','<=',$max_price)
    ->orWhereHas('brand',function($query){
        $query->whereIn('id', $brand_ids);
    })
    ->orWhereHas('suboptions',function($query){
        $query->whereIn('id', $suboptions_ids);
    })
    ->orWhereHas('subspecifications',function($query){
        $query->whereIn('id', $subspecifications_ids);
    })->get(); 
    

    $products will have products collection If any of the condition stated in above query matched.

    Hope this helps.

提交回复
热议问题