我在我的产品页面中展示了类似的产品。我有一个查询,查找所有正在查看的产品具有类似brand_id或cat_id的产品。我的问题是它还显示了在类似部分中查看的当前产品。我需要这样做,以便删除从类似产品部分查看的当前产品。
这是我现在的查询。 ('id','!==',$ product-> id部分无效)
/**
* Show a Product in detail
*
* @param $product_name
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function show($product_name) {
// Find the product by the product name in URL
$product = Product::ProductLocatedAt($product_name);
// Select All from "products" table where the brand_id is = to the current product being viewed with its brand_id, OR where
// the category_id is = to the current product category Id being viewed. This is so we can display similar products for a // particular product being shown.
$similar_product = Product::where('brand_id', '=', $product->brand_id)
->where('id', '!==', $product->id)
->orWhere('cat_id', '=', $product->cat_id)->get();
return view('pages.show_product', compact('product', 'similar_product'));
}
********编辑******** 我在使用您的查询方法时得到了这个:
答案 0 :(得分:2)
使用OR时请记住,Laravel的查询构建器默认情况下不添加括号。
https://laravel.com/docs/5.2/queries
您的查询最终会如下:
SELECT *
FROM products
WHERE brand_id = 1
AND id != 2
OR cat_id = 3
由于OR,结果包括基于其cat_id的产品。
你可能想要的是:
$similar_product = Product::where('id', '!=', $product->id)
->where(function ($query) use ($product) {
$query->where('brand_id', '=', $product->brand_id)
->orWhere('cat_id', '=', $product->cat_id);
})->get();
这会将OR部分放在一组括号内:
SELECT *
FROM products
WHERE id != 2
AND (brand_id = 1 OR cat_id = 3)
请记住,MySQL通常在优化OR子句方面做得不好。如果您的表很大,您可能需要仔细检查性能和索引使用情况。
答案 1 :(得分:0)
您是否尝试将!==更改为<>?
/**
* Show a Product in detail
*
* @param $product_name
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function show($product_name) {
// Find the product by the product name in URL
$product = Product::ProductLocatedAt($product_name);
// Select All from "products" table where the brand_id is = to the current product being viewed with its brand_id, OR where
// the category_id is = to the current product category Id being viewed. This is so we can display similar products for a // particular product being shown.
$similar_product = Product::where('brand_id', '=', $product->brand_id)
->where('id', '<>', $product->id) // changed this line..
->orWhere('cat_id', '=', $product->cat_id)->get();
return view('pages.show_product', compact('product', 'similar_product'));
}
!==不是MySQL的正确语法。
答案 2 :(得分:0)
我认为它不起作用,因为逻辑上你说的是
Brand ID equals AND product is not the same OR category equals
由于如果类别匹配,则没有定义优先级,该子句将为整个where语句返回true
您需要弄清楚如何对其进行分组,以便您的查询优先级如下
(ID is not the same) AND (brand matches OR category matches)