gpt4 book ai didi

php - ID 不等于正在查看的当前产品 ID - Laravel 5.2

转载 作者:行者123 更新时间:2023-11-29 06:14:25 25 4
gpt4 key购买 nike

我在我的产品页面中展示了类似的产品。我有一个查询,用于查找与正在查看的产品具有相似 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'));
}

********* 编辑 ********使用您的查询方法时我得到了这个:

Undefined你知道那可能是什么吗?

最佳答案

请记住,在使用 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 子句进行优化时做得不好。如果您的表很大,您可能需要仔细检查性能和索引使用情况。

关于php - ID 不等于正在查看的当前产品 ID - Laravel 5.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36668611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com