如何在 Laravel 中通过属性(颜色、尺寸等)过滤产品
P粉821274260
P粉821274260 2023-08-28 00:17:09
[PHP讨论组]
<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-&gt;bigIncrements('id'); $table-&gt;BigInteger('category_id')-&gt;unsigned()-&gt;nullable(); $table-&gt;string('name'); $table-&gt;string('code'); $table-&gt;integer('status')-&gt;default(1); $table-&gt;integer('featured')-&gt;default(1); $table-&gt;string('image'); $table-&gt;longText('short_description'); $table-&gt;longText('long_description'); $table-&gt;timestamps(); })</pre> <p><strong>产品属性表</strong></p> <pre class="brush:php;toolbar:false;">Schema::create('product_attributes', function (Blueprint $table) {. $table-&gt;bigIncrements('id'); $table-&gt;unsignedBigInteger('product_id'); $table-&gt;string('sku'); $table-&gt;string('size'); $table-&gt;string('color'); $table-&gt;string('price'); $table-&gt;string('stock'); $table-&gt;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-&gt;hasmany('App\Models\ProductAttributes', 'product_id'); } }</pre> <p><strong>我的刀片文件</strong></p> <pre class="brush:php;toolbar:false;">&lt;form action=&quot;{{url('/product/filter')}}&quot; method=&quot;post&quot;&gt; @csrf &lt;input type=&quot;hidden&quot;value=&quot;{{$slug}}&quot;name=&quot;slug&quot;&gt; &lt;div class=&quot;custom-control custom-checkbox d-flex align-items-center justify-content-between mb-3&quot;&gt; &lt;input name=&quot;color&quot; onchange=&quot;javascript:this.form.submit();&quot; type=&quot;radio&quot; class=&quot;custom-control-input&quot; id=&quot;black&quot; value=&quot;black&quot;&gt; &lt;label class=&quot;custom-control-label&quot; for=&quot;black&quot;&gt;Black&lt;/label&gt; &lt;/div&gt; &lt;/form&gt;</pre> <p>我的控制器中有一个函数</p> <pre class="brush:php;toolbar:false;">public function shop() { $filter_products = Product::with('attributes')-&gt;where(['category_id' =&gt; $category-&gt;id, 'color' =&gt; $request-&gt;color]); return view('frontend.shop', compact('filter_products')); }</pre> <p>应用此函数后我没有得到任何结果</p> <p>请指导我如何根据特定尺寸或颜色在前端商店页面过滤产品。 以及商店功能中将包含哪些代码。</p> <p>请回复我,我将非常感谢你</p>
P粉821274260
P粉821274260

全部回复(2)
P粉908138620
$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粉033429162

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

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]);
    });
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号