查询生成器生成错误查询

时间:2016-02-19 12:08:58

标签: php doctrine-orm

这是我的QueryBuilder

                        $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,因为它的灵活性,如何让它正常工作?

1 个答案:

答案 0 :(得分:0)

问题已解决。

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