如何在laravel中使用url查询过滤产品

问题描述

我有一个属性相关的产品表。

并且在所有产品页面中,我有一个过滤器部分用于过滤产品,此过滤器来自属性表,我需要知道如何通过 URL 设置此过滤器的查询,如下所示:

example.com/type=electronic&color=red&...

属性属性值有关系。

这是产品控制器:

public function index()
{
    $products = Product::query();

    if (request('category')) {
        $products->whereHas('categories',function ($query) {
            $query->where('id',request('category'));
        })->get();
    }

    if (request('brand')) {
        $products->whereHas('brand',function ($query) {
            $query->where('name',request('brand'));
        })->get();
    }

    $categories = Category::where('parent_id',0)->get();
    $products = $products->latest()->paginate(20);
    $brands = Brands::all();

    $filters = Category::where('id',request('category'))->first();

    return view('home.products.index',compact('products','categories','brands','filters'));
}

类别和属性之间还有一种关系,$filters 返回属于类别的属性

在产品型号中:

public function attributes()
{
    return $this->belongsToMany(Attribute::class)->using(ProductAttributeValues::class)->withPivot(['value_id']);
}

在类别模型中:

public function attributes()
{
    return $this->belongsToMany(Attribute::class);
}

属性模型中:

public function values()
{
    return $this->hasMany(AttributeValue::class);
}

这是侧栏中显示过滤器的视图:

@foreach($filters->attributes as $filter)
   @if($filter->filter == 1)
       <div class="filter-option">
           <p>
             {{ $filter->name }}
           </p>
           <div id="filter-section{{ $filter->id }}">
           @foreach($filter->values as $val)
              <div class="checkBox">
                   <input id="filter{{ $val->id }}" type="checkBox"
                          value="{{$filter->name}}={{ $val->value }}">
                   <label for="filter{{ $val->id }}">
                          {{ $val->value }}
                   </label>
              </div>
                @endforeach
            </div>
        </div>
   @endif
@endforeach

一个 foreach 用于属性名称,第二个 foreach 用于属性值属于属性

我知道我没有应用过滤器的任何东西,但我只需要知道什么是过滤器查询

谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)