php 我将如何在 Doctrine2 中执行 MySQL count(*)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12088026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:47:17  来源:igfitidea点击:

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

phpmysqlsymfonydoctrine-orm

提问by matthew

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 count(*)?

回答by Asciiom

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();

回答by Boris Guéry

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 NativeQuerysince your result is a simple scalar not an object.

但是,如果您需要性能,您可能需要使用 a,NativeQuery因为您的结果是一个简单的标量而不是一个对象。

回答by SudarP

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 块

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