Laravel advanced search query fix

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

    Here's how I'd do it. Note the use of when for simplifying optional where conditions (no need to set variables either), and the closure for constraining both the whereHas and the with (if you want to eager load the relationships).

    $products = Product::query()
        ->when($request->min_price, function ($query, $min_price) {
            return $query->where('price', '>=', $min_price);
        })
        ->when($request->max_price, function ($query, $max_price) {
            return $query->where('price', '<=', $max_price);
        })
        ->when($request->suboptions, function ($query, $suboptions) {
            $suboptionsConstraint = function ($q) use ($suboptions) {
                return $q->whereIn('id', $suboptions);
            };
            return $query->whereHas('suboptions', $suboptionsContraint)
                ->with(['suboptions' => $suboptionsContraint]);
        })
        ->when($request->brands, function ($query, $brands) {
            $brandsConstraint = function ($q) use ($brands) {
                return $q->whereIn('id', $brands);
            };
            return $query->whereHas('brands', $brandsConstraint)
                ->with(['brands' => $brandsConstraint]);
        });
    

提交回复
热议问题