【问题标题】:Laravel - getting results from products table where i'm matching the results with attributes tableLaravel - 从产品表中获取结果,我将结果与属性表匹配
【发布时间】:2021-06-20 07:58:44
【问题描述】:

我有这些表

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

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

这是我在 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'));
    }

【问题讨论】:

  • 您要搜索的记录是否必须与 $tasteArray 中的所有值匹配,或者如果它至少匹配其中一个值,则应将其包含在结果中?

标签: php mysql laravel relationship


【解决方案1】:

你可以这样做。

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

【讨论】:

  • 这对我来说非常有效,只需将use ($item) 添加到function($query) 谢谢
  • 是的,对不起,我忘了。
猜你喜欢
  • 2016-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
相关资源
最近更新 更多