简体   繁体   English

我如何在Doctrine2中进行MySQL计数(*)?

[英]How would I do MySQL count(*) in Doctrine2?

I have the following Doctrine2 query: 我有以下Doctrine2查询:

$qb = $em->createQueryBuilder()
      ->select('t.tag_text, COUNT(*) as num_tags')
      ->from('CompanyWebsiteBundle:Tag2Post', 't2p')
      ->innerJoin('t2p.tags', 't')
      ->groupBy('t.tag_text')
;
$tags = $qb->getQuery()->getResult();

When run I get the following error: 运行时,我收到以下错误:

[Semantical Error] line 0, col 21 near '*) as num_tags': Error: '*' is not defined. 

How would I do MySQL count(*) in Doctrine2? 我如何在Doctrine2中进行MySQL计数(*)?

You should be able to do it just like this (building the query as a string): 您应该能够像这样(将查询构建为字符串):

$query = $em->createQuery('SELECT COUNT(u.id) FROM Entities\User u');
$count = $query->getSingleScalarResult();

You're trying to do it in DQL not "in Doctrine 2". 你试图用DQL而不是“在Doctrine 2中”。

You need to specify which field (note, I don't use the term column) you want to count, this is because you are using an ORM, and need to think in OOP way. 您需要指定要计算的字段(注意,我不使用术语列),这是因为您使用的是ORM,需要以OOP方式进行思考。

$qb = $em->createQueryBuilder()
      ->select('t.tag_text, COUNT(t.tag_text) as num_tags')
      ->from('CompanyWebsiteBundle:Tag2Post', 't2p')
      ->innerJoin('t2p.tags', 't')
      ->groupBy('t.tag_text')
;
$tags = $qb->getQuery()->getResult();

However, if you require performance, you may want to use a NativeQuery since your result is a simple scalar not an object. 但是,如果需要性能,则可能需要使用NativeQuery因为结果是简单的标量而不是对象。

As $query->getSingleScalarResult() expects at least one result hence throws a no result exception if there are not result found so use try catch block 因为$ query-> getSingleScalarResult()期望至少有一个结果因此如果没有找到结果则抛出无结果异常,所以使用try catch block

try{
   $query->getSingleScalarResult();
}
catch(\Doctrine\ORM\NoResultException $e) {
        /*Your stuffs..*/
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM