php Symfony2 & Doctrine - 获取从数据源返回的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8226874/
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
Symfony2 & Doctrine - Get number of rows returned from datasource
提问by Matt
I have the following code in my Symfony2 Repository Class...
我的 Symfony2 存储库类中有以下代码...
$query = $this->createQueryBuilder('foo')
->where('foo.bar = :id')
->setParameter('id', $myID)
->getQuery();
How do I get the number of rows found by the database?
如何获取数据库找到的行数?
Thanks in advance
提前致谢
回答by Reuven
You need to execute DQL to do something you want.
你需要执行 DQL 来做你想做的事情。
$query = $this->createQueryBuilder()
->from('foo', 'f')
->where('foo.bar = :id')
->setParameter('id', $myID)
->getQuery();
$total = $query->select('COUNT(f)')
->getQuery()
->getSingleScalarResult();
回答by pixyz
I think you can do something like that:
我认为你可以这样做:
$query = $this->createQueryBuilder()
->select('COUNT(f.id)')
->from('foo', 'f')
->where('foo.bar = :id')
->setParameter('id', $myID)
->getQuery();
$total = $query->getSingleScalarResult();
回答by Matt
You execute the query then get the results. When you have the results, you get the number of record by doing a count
on the results:
您执行查询然后获取结果。获得结果后,您可以通过count
对结果执行 a来获得记录数:
$results = $query->getResult();
$resultCount = count($results);
If you are concerned with paging, like getting 25 records out of the total. Then, you have two choices.
如果您关心分页,例如从总数中获取 25 条记录。那么,你有两个选择。
You perform the query twice, one time to get total results, another time to retrieve only 25 results using the method
setFirstResult
andsetMaxResults
. This methodsetFirstResult
enable you to set the offset and the second,setMaxResults
, number of records. The following code will give you results ranging from 25 to 50, it's the second page if you use 25 records by page.$query->setFirstResult(25);
$query->setMaxResults(25);
You can check doctrine-extensions for Doctrine2 which have paginator support. These extensions have been made by one of the developer of Doctrine2. You can review these here.
您执行查询两次,一次获得总成绩,其他时间只检索25使用该方法的结果
setFirstResult
和setMaxResults
。此方法setFirstResult
使您能够设置偏移量和第二个setMaxResults
记录数。以下代码将为您提供从 25 到 50 的结果,如果您逐页使用 25 条记录,则它是第二页。$query->setFirstResult(25);
$query->setMaxResults(25);
您可以检查具有分页器支持的 Doctrine2 的学说扩展。这些扩展是由 Doctrine2 的开发人员之一完成的。您可以在此处查看这些内容。
Hope this help.
希望这有帮助。
Regards,
Matt
问候,
马特
回答by Casey
I think this is as concise as it gets:
我认为这很简洁:
$qb = $repo->createQueryBuilder('entity');
$qb->select('COUNT(entity)');
$count = $qb->getQuery()->getSingleScalarResult();
Where $repo
is of type Doctrine\ORM\EntityRepository
哪里$repo
是类型Doctrine\ORM\EntityRepository