Laravel - 从产品 table 获取结果,我将结果与属性 table 进行匹配

Laravel - getting results from products table where i'm matching the results with attributes table

我有这些 tables

| products |                 | products_attributes |

id name and ..                id  product_id taste expire

产品型号

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

ProductAtributes 模型

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

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

这是我在Controller中的过滤函数

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

你可以这样做。

$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."%");
    });
  }
}