【问题标题】:Laravel ecommerce dynamic product filteringLaravel 电子商务动态产品过滤
【发布时间】:2021-03-15 17:30:53
【问题描述】:

我有一个巨大的问题,我找不到解决方法。我正在使用 Laravel 构建一个电子商务应用程序,构建一个良好的产品过滤系统至关重要。我有 productsattributes 具有多对多关系的表。数据透视表product_attribute 有额外的value(如果attribute 是颜色,则value 将是red)列。当进入商店页面时,有一个带有过滤选项的侧边栏。我可以显示的唯一选项是 brand,因为它与产品表是一对多的关系。显示这些属性的正确方法是什么。正如我提到的,属性对于页面上的产品应该是动态的。不同类别的不同产品(自行车、衣服、球、台球桌)可能具有不同的属性。

public function show($slug){

  // Get products with attributes for specic 
  $category = Category::with('products')->where('slug',$slug)->firstOrFail();

  // Collect brand ids
  $b_ids = array_filter($category->products->pluck('brand_id')->toArray());

  //Get brands to show in the filtering options
  $brands = Brand::whereIn('id',$b_ids)->get();

  $attributes = ?

  return view('front.shop', compact('category','brands', 'attributes'));
  }

【问题讨论】:

    标签: laravel many-to-many e-commerce


    【解决方案1】:

    产品的急切加载属性 - Category::with('products.attributes')

    public function show($slug){
    
      // Get products with attributes for specic 
      $category = Category::with('products.attributes')->where('slug',$slug)->firstOrFail();
    
      // Collect brand ids
      $b_ids = array_filter($category->products->pluck('brand_id')->toArray());
    
      //Get brands to show in the filtering options
      $brands = Brand::whereIn('id',$b_ids)->get();
    
     
    
      return view('front.shop', compact('category','brands'));
    }
    

    然后在视图中属性可以通过产品访问

    这不是我想要的。它只是给了我价值。我希望属性名称显示在顶部(例如颜色),值(红色、蓝色等)显示在底部的复选框旁边,供用户过滤

    假设您将属性的所有可能值存储为选项

    // ...
    
    @foreach($categories as $category)
       @foreach($category->products as $product)
            @include('attribute-options', ['attributes' => $product->attributes])
        @endforeach
    @endforeach
    
    // ... 
    

    将产品的属性显示提取到部分 - attribute-options.blade.php

    @foreach($attributes as $attribute)
        <h3>{{ $attribute->name }}
        <ul>
            @foreach($attribute->options as $option)
                <li>
                    <label for="{{$attribute->name}}-{{$option}}">{{ $option }}
                        <input 
                          type="radio" 
                          value="{{$option}}"
                          id="{{$attribute->name}}-{{$option}}"
                          name="{{$attribute->name}}-{{$option}}"
                        />
                    </label>
                </li>
            @endforeach
        </ul>
    @endforeach
    

    【讨论】:

    • 这不是我想要的。它只是给了我价值。我希望属性名称显示在顶部(例如颜色)和值(红色、蓝色等)在用户过滤复选框旁边的底部
    • @Mirzəyevİsmayıl 已根据您的上述评论更新了答案
    • 这会产生重复,就像过滤器上有 3 个颜色部分一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2013-06-15
    • 2020-07-12
    • 2011-10-07
    • 1970-01-01
    • 2017-02-07
    • 2017-12-16
    相关资源
    最近更新 更多