Rumah > Soal Jawab > teks badan
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
Anda perlu menapis mengikut perhubungan, sila semak dokumentasi
https://laravel.com/docs/9 .x/eloquent-relationships#querying-relationship-existence
Contoh Gunakan WhereHas
$filter_products = Product::with('attributes') ->where(['category_id' => $category->id]) ->whereHas('attributes',function($query) use($request){ $query->where(['color' => $request->color]); });
Jika tidak digunakan di mana-mana, semua harta akan dikembalikan
Anda boleh menghalang tingkah laku ini menggunakan penapis yang sama digunakan di 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]); });