编程语言
首页 > 编程语言> > php-如何使用Doctrine @ ORM在一个DQL查询中进行多个计数?

php-如何使用Doctrine @ ORM在一个DQL查询中进行多个计数?

作者:互联网

我正在尝试使用Doctrine2 ORM在一个DQL查询中进行多个计数.

这是我的查询内容:

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('

SELECT      COUNT(u.id) AS users,
            COUNT(t.id) AS teams,
            COUNT(p.id) AS posts,
            COUNT(c.id) AS comments
    FROM    ProjectUserBundle:User u,
            ProjectTeamBundle:Team t,
            ProjectPostBundle:Post p,
            ProjectCommentBundle:Comment c,
            ');
$counts = $query->getSingleResult();

它返回以下结果:
{“用户”:“ 2648940”,“团队”:“ 2648940”,“帖子”:“ 2648940”,“评论”:“ 2648940”}

它一定是这样的:
{“ users”:“ 17”,“ teams”:“ 5”,“ posts”:“ 190”,“ comments”:“ 321”}

有人可以告诉我我在哪里做错了?

解决方法:

通过查询,DQL会混合使用表,而不是对每个表中的行进行计数.结果是错误的行数.它无法解释原因和方式,但是当我在查询中使用多个COUNT()函数时,它总是失败.

要计算正确的行数,您必须使用子查询:

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('

SELECT      COUNT(U.id) AS users,
            (SELECT COUNT(T) FROM ProjectUserBundle:Team T) AS teams,
            (SELECT COUNT(P) FROM ProjectUserBundle:Post P) AS posts,
            (SELECT COUNT(C) FROM ProjectUserBundle:Comment C) AS comments
    FROM    ProjectUserBundle:User U
            ');

$counts = $query->getSingleResult();

标签:dql,symfony,doctrine,php
来源: https://codeday.me/bug/20191122/2059811.html