P粉9081386202023-08-28 15:59:41
$brands = Brand::orderBy('id','DESC')->get(); $colors = Color::orderBy('id','DESC')->get(); $sizes = Size::orderBy('id','DESC')->get(); $weights = Weight::orderBy('id','DESC')->get(); $tags = Tag::orderBy('id','DESC')->get(); try{ if (!empty($_GET['colors']) || !empty($_GET['brands']) || !empty($_GET['sizes']) || !empty($_GET['weights']) || !empty($_GET['tags'])) { $products = Product::where( function($query ){ $query->when(!empty(request()->colors) ,function($subquery){ $subquery->whereHas('colors', function($subquery) { $subquery->whereIn('colors.id',request()->colors); }); })->when(!empty(request()->sizes) ,function($subquery){ $subquery->whereHas('sizes', function($subquery) { $subquery->whereIn('sizes.id',request()->sizes); }); })->when(!empty(request()->weights) ,function($subquery){ $subquery->whereHas('weights', function($subquery) { $subquery->whereIn('weights.id',request()->weights); }); })->when(!empty(request()->tags) ,function($subquery){ $subquery->whereHas('tags', function($subquery) { $subquery->whereIn('tags.id',request()->tags); }); })->when(!empty(request()->brands) ,function($subquery){ $subquery->whereHas('brand', function($subquery) { $subquery->whereIn('brand_id',request()->brands); }); })->when(!empty(request()->is_new) ,function($subquery){ $subquery->where('is_new',request()->is_new); })->when(!empty(request()->gender) ,function($subquery){ $subquery->where('gender', 'LIKE', "%" . request()->gender . "%"); }); })->paginate(10); return view('front.shop',compact('products','brands','colors','sizes','weights','tags')); } else { return redirect()->route('products'); } } catch (\Exception $e) { toastr()->error(trans('Some thing is wrong please try again')); return redirect()->route('products'); }
P粉0334291622023-08-28 13:52:36
您需要按關係過濾,請查看文件
https://laravel.com/docs/9 .x/eloquent-relationships#querying-relationship-existence
#舉例說明 使用WhereHas
$filter_products = Product::with('attributes') ->where(['category_id' => $category->id]) ->whereHas('attributes',function($query) use($request){ $query->where(['color' => $request->color]); });
如果 with 中沒有應用任何地方,則會傳回所有屬性
您可以使用 whereHas 中套用的相同篩選器來防止這種行為
$filter_products = Product::with(['attributes'=>function($query) use($request){ $query->where(['color' => $request->color]); }]) ->where(['category_id' => $category->id]) ->whereHas('attributes',function($query) use($request){ $query->where(['color' => $request->color]); });