3
我試圖運行此查詢:如何在使用Eloquent查詢生成器的同一張表上使用whereHas?
$products = $this->product_model->where(function($query) use ($key) {
$query->whereHas('categories', function ($category) use ($key) {
$category->where('key', $key);
});
$query->orWhereHas('parent.categories', function ($category) use ($key) {
return $category->where('key', $key);
});
});
父關係是另一種產品,因此它從同一個表的。我遇到的問題是,這會產生查詢:
SELECT *
FROM `products`
WHERE (
(SELECT count(*)
FROM `categories`
INNER JOIN `category_product` ON `categories`.`id` = `category_product`.`category_id`
WHERE `category_product`.`product_id` = `products`.`id`
AND `key` = 'mens'
) >= 1
OR
(SELECT count(*)
FROM `products` AS `self_30ec5d4782a83841add518f618b9f59e`
WHERE `self_30ec5d4782a83841add518f618b9f59e`.`id` = `products`.`parent_product_id`
AND
(SELECT count(*)
FROM `categories`
INNER JOIN `category_product` ON `categories`.`id` = `category_product`.`category_id`
WHERE `category_product`.`product_id` = `products`.`id`
AND `key` = 'mens'
) >= 1
) >= 1
)
在子查詢後,或我需要這行:
WHERE `category_product`.`product_id` = `products`.`id`
是這樣的:
WHERE `category_product`.`product_id` = `self_30ec5d4782a83841add518f618b9f59e`.`id`
當我在數據庫上運行此SQL時,我得到正確的結果:
SELECT *
FROM `products`
WHERE (
(SELECT count(*)
FROM `categories`
INNER JOIN `category_product` ON `categories`.`id` = `category_product`.`category_id`
WHERE `category_product`.`product_id` = `products`.`id`
AND `key` = 'mens'
) >= 1
OR
(SELECT count(*)
FROM `products` AS `self_30ec5d4782a83841add518f618b9f59e`
WHERE `self_30ec5d4782a83841add518f618b9f59e`.`id` = `products`.`parent_product_id`
AND
(SELECT count(*)
FROM `categories`
INNER JOIN `category_product` ON `categories`.`id` = `category_product`.`category_id`
WHERE `category_product`.`product_id` = `self_30ec5d4782a83841add518f618b9f59e`.`id`
AND `key` = 'mens'
) >= 1
) >= 1
)
但我不知道如何讓它在我的PHP代碼中做到這一點。此外,這是預期的SQL輸出?它不應該做我想做的事嗎?由於子查詢位於whereHas?
謝謝,我確實開始認爲這可能是一個錯誤,但沒有時間(或可能的能力!)進一步調查它自己。 –