php Symfony 2 学说 COUNT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23971570/
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
Symfony 2 Doctrine COUNT
提问by Macbernie
I have in my table "Artiste" one column "valideAdmin" who takes value 1 or 0.
我的表“Artiste”中有一个列“valideAdmin”,其值为 1 或 0。
I try to make a simple count to return the number of entries in my table where "valideAdmin" is to 1:
我尝试做一个简单的计数,以返回我的表中“valideAdmin”为 1 的条目数:
$repo = $this ->getDoctrine()
->getManager()
->getRepository('ProjectMainBundle:Artiste');
$qb = $repo->createQueryBuilder('valideAdmin');
$qb->select('COUNT(valideAdmin)');
$qb->where('valideAdmin=1');
$count = $qb->getQuery()->getSingleScalarResult();
return array(
'count' => $count
);
But it always "1" who's return...
但它总是“1”谁回来......
Without where clause, I have the total count of the entries of the table, but valideAdmin can be 0 or 1. I only want the count number where valideAdmin=1
没有where子句,我有表的条目总数,但valideAdmin可以是0或1。我只想要valideAdmin = 1的计数数字
Thanks for help
感谢帮助
回答by Andrew Moore
createQueryBuilder()
's first parameter is the alias
that you want your entity to take (ie.: a short name to be used to refer to your entity in the query).
createQueryBuilder()
的第一个参数是alias
您希望实体采用的参数(即:用于在查询中引用您的实体的短名称)。
What you need to do is set a proper alias for your entity (for example a
for Artiste
) and then COUNT()
the instances of your entity where the property(not the column) valideAdmin
is set to one:
您需要做的是为您的实体设置一个适当的别名(例如a
for Artiste
),然后COUNT()
将您的实体的实例设置为一个属性(而不是列)valideAdmin
:
$repo = $this ->getDoctrine()
->getManager()
->getRepository('ProjectMainBundle:Artiste');
$qb = $repo->createQueryBuilder('a');
$qb->select('COUNT(a)');
$qb->where('a.valideAdmin = :valideAdmin');
$qb->setParameter('valideAdmin', 1);
$count = $qb->getQuery()->getSingleScalarResult();
Remember that DQL
runs queries on entities. The DQL
your write is then translated into SQL
to query the underlying data source after.
请记住,DQL
在实体上运行查询。将DQL
那么你写被翻译成SQL
查询后的基础数据源。
回答by pedram shabani
Also you can fetch all date then use of COUNTfunction in PHPThis method has an advantage.You do not have to use a complex query. You have all the information with count columns
您也可以获取所有日期,然后在PHP 中使用COUNT函数 这种方法有一个优势。您不必使用复杂的查询。您拥有计数列的所有信息
$repositoryArtiste = $this->getDoctrine()
->getRepository('ProjectMainBundle:Artiste');
$queryArtiste= $repositoryArtiste->createQueryBuilder('a')
->Where('a.valideAdmin = :valideAdmin')
->setParameter('valideAdmin',1)
->getQuery();
$Artiste = $queryArtiste->getResult();
var_dump(count($Artiste));