如何在与Eloquent Query Builder的同一个表的关系中使用whereHas?

时间:2016-01-20 19:41:23

标签: php mysql laravel eloquent

我试图运行此查询:

$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
)

在OR之后的子查询中我需要这一行:

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?

1 个答案:

答案 0 :(得分:1)

这是Laravel中的一个错误。 has() / whereHas()无法正确处理自我关系或嵌套自我关系的条件。

我已提交拉取请求以更正此问题。您可以查看here

我不知道它是否会被接受,但您可以查看它以查看已更改的代码,并决定是否要自行手动更新Laravel。您也可以关注它并等待结果。