【问题标题】:query builder generates incorrect query查询生成器生成不正确的查询
【发布时间】:2016-02-19 12:08:57
【问题描述】:

这是我的查询生成器

                        $qb->select('u')
                            ->from(Victim::class,'u')
                            ->join('u.tags','t')
                            ->where('t.id in (11,15)')
                            ->groupBy('u.id')
                            ->having('count(u.id)=2');

生成错误的 SQL 查询(查看 FROM 子句)

    SELECT
      v0_.id           AS id_0,
      v0_.avatarUrl    AS avatarurl_1,
      v0_.displayName  AS displayname_2,
      v0_.summary      AS summary_3,
      v0_.gender       AS gender_4,
      v0_.birthDay     AS birthday_5,
      v0_.maritalState AS maritalstate_6,
      v0_.folder_id    AS folder_id_7
   FROM victims v1_, victims v0_ 
   INNER JOIN victim_tag v3_ ON v0_.id = v3_.victim_id
   INNER JOIN tags t2_ ON t2_.id = v3_.tag_id
   WHERE t2_.id IN (11,15)
   GROUP BY v0_.id
   HAVING count(v0_.id) = 2

但是当我使用 DQL 时

                        $qry = sprintf(
                            'SELECT u FROM %s u JOIN u.%s t WHERE t.id IN (%s) GROUP BY u.id HAVING count(u.id)= %s ORDER BY u.id DESC',
                            Victim::class,
                            $key,
                            implode(',', $value),
                            count($value)
                        );

查询结果正常

SELECT
  v0_.id           AS id_0,
  v0_.avatarUrl    AS avatarurl_1,
  v0_.displayName  AS displayname_2,
  v0_.summary      AS summary_3,
  v0_.gender       AS gender_4,
  v0_.birthDay     AS birthday_5,
  v0_.maritalState AS maritalstate_6,
  v0_.folder_id    AS folder_id_7
FROM victims v0_ INNER JOIN victim_tag v2_ ON v0_.id = v2_.victim_id
  INNER JOIN tags t1_ ON t1_.id = v2_.tag_id
WHERE t1_.id IN (11, 15)
GROUP BY v0_.id
HAVING count(v0_.id) = 2
ORDER BY v0_.id DESC;

我有点困惑。我想在这里使用 QueryBuilder 是因为它的灵活性,如何让它正常工作?

【问题讨论】:

  • 您是否在 RepositoryClass 中使用查询生成器?您是否覆盖了 getAlias() 方法?你可以在里面发布你的课程吗?
  • @ViniciusZaramella 不,它在存储库类之外,并且存储库类中的任何内容都没有被覆盖。
  • 你是如何实例化 $qb 的?我认为您可以擦除 ->select('u')->from('...) 并保留加入后的内容。
  • @ViniciusZaramella 我解决了这个问题(更新后)。谢谢帮助

标签: php doctrine-orm


【解决方案1】:

问题已解决。

$qb->add('select', 'u')
    ->add('from', Victim::class . ' u')
    ->join('u.tags','t')
    ->add('where', 't.id in (11,15)')
    ->add('groupBy', 'u.id')
    ->add('having', 'count(u.id)=2');

【讨论】:

    猜你喜欢
    • 2019-09-11
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多