【问题标题】:Doctrine 2: Count Items by Type in Select原则 2:在 Select 中按类型计算项目
【发布时间】:2012-01-01 09:02:15
【问题描述】:

有谁知道如何根据 Doctrine 2 QueryBuilder select() 语句中的条件检索计数?

这是我迄今为止尝试过的......

我的第一次尝试是尝试 count() 和 eq()。我收到的错误是“预期的右括号,等于。”

$qb->select($qb->expr()->count($qb->expr()->eq('t.id', '1')))

接下来我尝试了 count() 和 have()。我收到的错误是“达到最大函数嵌套级别”。

$qb->select($qb->expr()->count($qb->having('t.id', '1')))

然后我用 where() 和 eq() 尝试了 count()。我再次得到“达到最大函数嵌套级别。”

$qb->select($qb->expr()->count($qb->where($qb->expr()->eq('t.id', '1'))))

然后我使用 in() 尝试了这些变化。他们都给出了语法错误“Expected FROM, got '('

$qb->select($qb->expr()->count($qb->expr()->in('t.id', array(1))))
$qb->select($qb->expr()->count($qb->expr()->in('t.id', 1)))

对于 in() 示例,我还尝试通过 setParameter() 将值作为变量传递,结果相同。

这是我尝试在 QueryBuilder 中编写的 MySQL 等价物:

SELECT
    SUM(IF(type.id = 1, 1, 0)) AS 'fords',
    SUM(IF(type.id = 2, 1, 0)) AS 'hondas'
FROM item
JOIN type ON item.type_id = type.id

【问题讨论】:

  • 别忘了,你可以使用原生查询。有时它更快、更优雅。

标签: php mysql doctrine doctrine-orm subquery


【解决方案1】:

除非您需要继续使用 DQL,否则这可能会有所帮助:

public function MyAction() {

    $this->doctrineContainer = Zend_Registry::get('doctrine');
    $em = $this->doctrineContainer->getEntityManager(); 

    $fords = $em->getRepository('My\Entity\Item')->findBy(array('type' => '1'));
    $hondas = $em->getRepository('My\Entity\Item')->findBy(array('type' => '2'));

    $fordQty = count($fords);
    $hondaQty = count($hondas);

}

一些细节在:http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-objects.html#by-simple-conditions

【讨论】:

  • 感谢 Froger - 我最终编写了一个本地查询,但我相信这也会派上用场。
  • @cantera 很高兴与我们分享本机查询,因为这可能对遇到相同问题的人有所帮助。
  • 这对于许多记录来说并不适用,因为它在 PHP 中使用大量内存来存储这个数组然后计算它
【解决方案2】:

使用 QueryBuilder,试试:

$qb->select(" SUM(CASE WHEN t.id = 1 THEN 1 ELSE 0 END) as fords ")
->addSelect(" SUM(CASE WHEN t.id = 2 THEN 1 ELSE 0 END) as hondas ")

【讨论】:

    【解决方案3】:

    使用查询生成器:

    $query = $respository
            ->createQueryBuilder('u')
            ->select('count(u)')
            ->getQuery()
    ;
    
    $total = $query->getSingleResult();
    

    :)

    【讨论】:

    • 最好按如下方式获得计数:$total = $query->getSingleScalarResult();
    猜你喜欢
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 2013-09-03
    • 2015-09-28
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    相关资源
    最近更新 更多