首页 > 解决方案 > Laravel - 从产品表中获取结果,我将结果与属性表匹配

问题描述

我有这些桌子

| products |                 | products_attributes |

id name and ..                id  product_id taste expire

产品型号

public function attributes(){
        return $this->hasMany(ProductsAttributes::class);
    }

产品属性模型

 public function product(){
        return $this->belongsTo(Product::class);
    }

所有其他属性都在产品表中,可以轻松地将它们添加到过滤器查询中,但我不知道如何将带有口味过滤器的产品添加到查询中,因为口味在属性表中。

这是我在控制器中的过滤功能

public function showCategory(Request $request, $id){
        $catt = Category::findorfail($id);
        $products = Product::where('category_id', $catt->id)->where('status', '1')
            ->orderBy('brand_id', 'ASC');

        if(!empty($_GET['brand'])){
            $brandArray = explode('-', $_GET['brand']);
            $products = $products->whereIn('brand_id', $brandArray);
        }

        if(!empty($_GET['weight'])){
            $weightArray = explode('-', $_GET['weight']);
            $products = $products->whereIn('product_weight', $weightArray);
        }

        if(!empty($_GET['count'])){
            $countArray = explode('-', $_GET['count']);
            $products = $products->whereIn('product_count', $countArray);
        }

        if(!empty($_GET['taste'])){
            $tasteArray = explode(',', $_GET['taste']);
            foreach ($tasteArray as $taste){
                $attr = ProductsAttributes::where('product_taste','LIKE', "%$taste%")->with('product')->get();

                $products = $products->merge($attr);
            }
        }

        if(!empty($_GET['sort'])){
            $sort = $_GET['sort'];
            $products = $products->reorder('selling_price', $sort);
        }

        $products = $products->paginate(12);

        return view('pages.show_category', compact('products', 'catt'));
    }

标签: phpmysqllaravelrelationship

解决方案


你可以这样做。

$products = Product::orderBy("id","ASC");

if(!empty($_GET['taste']){
  $tasteArray = explode(',', $_GET['taste']);
  foreach($tasteArray as $item){
    $products = $products->whereHas("attributes",function($query) use($item){
       $query->where("taste","LIKE","%".$item."%");
    });
  }
}

推荐阅读