php - 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'));
}
解决方案
你可以这样做。
$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."%");
});
}
}
推荐阅读
- javascript - 如何在返回值之前等待 Cypress then() 命令完成?
- sql - 用于发送电子邮件 dbmail 的用户授权
- c# - FirstOrDefault() 导致 Collection 被修改;枚举操作可能无法执行。例外
- snowflake-sql - 在特定事件之后的行 FOR A KEY
- php - 使用googlespreadsheet api v4批量更新单个单元格?
- r - 如何使用 R 中的 Hayes Process 更改调解调解的调解人值
- algorithm - 对于两个非负函数 f 和 g,如果 f = O(g) 和 g = O(f) 并且 ∀n,f(n) > g(n) 则证明或反证 f - g = O(1)
- reactjs - 如果提供了某些值,有没有办法使所需的打字稿值可选?
- firebase - 我遇到“错误:没有为类型“对象”定义运算符“[]”。我该如何解决这个问题?
- azure - Azure 二头肌资源模块的依赖性问题