【问题标题】:How to filter Products through attributes (color, size etc.) in Laravel如何在 Laravel 中通过属性(颜色、尺寸等)过滤产品
【发布时间】:2023-02-11 03:29:38
【问题描述】:

我是 Laravel 的新手,想过滤掉特定的产品。

我的数据库中有两个表,第一个是表products,第二个是表attributes。

产品表

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

产品属性表

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

关系

因为我有单一产品的多个属性

class Product extends Model
{
    use HasFactory;

    public function attributes()
    {
         return $this->hasmany('App\Models\ProductAttributes', 'product_id');
    }
}

我的刀片文件

<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="black" value="black">   <label class="custom-control-label" for="black">Black</label>
</div>

</form>

我的控制器中有一个功能

public function shop()
{

$filter_products = Product::with('attributes')->where(['category_id' => $category->id, 'color' => $request->color]);

    return view('frontend.shop', compact('filter_products'));
}

应用此功能后,我没有得到任何结果

请指导我如何根据特定尺寸或颜色在我的前端商店页面上过滤产品。 以及商店功能中的代码。

请回复我会非常感谢你

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您需要按关系过滤,请查看文档

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

    如果在没有应用的地方,这将返回所有属性

    您可以使用在 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]);
        });
       
    

    【讨论】:

    • 添加了一些建议更正。
    【解决方案2】:
        $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');
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-30
      • 2015-12-20
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多