Laravel advanced search query fix

后端 未结 8 1328
终归单人心
终归单人心 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:10

    I suggest a different approach.

    On your controller, change it to this:

    public function advancedsearch(Request $request) {
    
    $suboptions2 = request->suboptions ? request->suboptions : null;
    $min_price = request->min_price ? request->min_price : null;
    $max_price = request->max_price ? request->max_price : null;
    $brands2 = request->brands ? request->brands : null;
    
    $query = Product::select('field_1', 'field_2', 'field_3')
    ->join('brands as b', 'b.id', '=', 'products.brand_id')
    ...(others joins);
    
    // here we do the search query
    if($suboptions2){
        $query->where('suboptions_field', '=', $suboptions);
    }
    
    if($min_price && $max_price){
        $query->where(function($q2) {
                    $q2->where('price', '>=', $min_price)
                        ->where('price', '<=', $max_price)
                });
    
    }
    
    if($brands2){
        $query->where('products.brand_id', '=', $brands2);
    }
    
    // others queries
    
    // finish it with this
    $query->get();
    
    return view('front.advancesearch', compact('products', 'brands', 'options'));
    

    I find doing it this way is very useful because it can be really easy to implement additional queries.

提交回复
热议问题