首頁  >  問答  >  主體

如何在 Laravel 中透過屬性(顏色、尺寸等)過濾產品

<p>我是 Laravel 新手,想要過濾掉特定產品。 </p> <p>我的資料庫中有兩個表,第一個是表<code>products</code>,第二個是表<code>attributes</code>。 </p> <p><strong>產品表</strong></p> <pre class="brush:php;toolbar:false;">Schema::create('products', function (Blueprint $table) { $table->bigIncrements('id'); $table->BigInteger('category_id')->unsigned()->nullable(); $table->string('name'); $table->string('code'); $table->integer('status')->default(1); $table->integer('featured')->default(1); $table->string('image'); $table->longText('short_description'); $table->longText('long_description'); $table->timestamps(); })</pre> <p><strong>產品屬性表</strong></p> <pre class="brush:php;toolbar:false;">Schema::create('product_attributes', function (Blueprint $table) {. $table->bigIncrements('id'); $table->unsignedBigInteger('product_id'); $table->string('sku'); $table->string('size'); $table->string('color'); $table->string('price'); $table->string('stock'); $table->timestamps(); })</pre> <p><strong>關係</strong></p> <p>因為我有單一產品的多個屬性</p> <pre class="brush:php;toolbar:false;">class Product extends Model { use HasFactory; public function attributes() { return $this->hasmany('App\Models\ProductAttributes', 'product_id'); } }</pre> <p><strong>我的刀片檔案</strong></p> <pre class="brush:php;toolbar:false;"><form action="{{url('/product/filter')}}" method="post"> @csrf <input type="hidden"value="{{$slug}}"name="slug"> <div class="custom-control custom-checkbox d-flex align-items-center justify-content-between mb-3"> <input name="color" onchange="javascript:this.form.submit();" type="radio" class="custom-control-input" id=" class="custom-control-input" id=" ;black"> <label class="custom-control-label" for="black">Black</label> </div> </form></pre> <p>我的控制器中有一個函數</p> <pre class="brush:php;toolbar:false;">public function shop() { $filter_products = Product::with('attributes')->where(['category_id' => $category->id, 'color' => $request->color]); return view('frontend.shop', compact('filter_products')); }</pre> <p>應用此函數後我沒有得到任何結果</p> <p>請指導我如何根據特定尺寸或顏色在前端商店頁面過濾產品。 以及商店功能中將包含哪些代碼。 </p> <p>請回覆我,我會非常感謝你</p>
P粉821274260P粉821274260391 天前537

全部回覆(2)我來回復

  • P粉908138620

    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');
        }

    回覆
    0
  • P粉033429162

    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]);
        });

    回覆
    0
  • 取消回覆