问题描述
我如何计算带有条件的实体的项目?例如,我意识到我可以使用:
How can I count an entity's items with a condition in Doctrine? For example, I realize that I can use:
$usersCount = $dm->getRepository('User')->count();
但这只会计算所有用户。我只想统计那些类型为employee的人员。我可以做这样的事情:
But that will only count all users. I would like to count only those that have type employee. I could do something like:
$users = $dm->getRepository('User')->findBy(array('type' => 'employee'));
$users = count($users);
这可行,但并非最佳选择。是否有以下内容:?
That works but it's not optimal. Is there something like the following:?
$usersCount = $dm->getRepository('User')->count()->where('type', 'employee');
推荐答案
那么,您可以使用来设置 COUNT
个查询:
Well, you could use the QueryBuilder to setup a COUNT
query:
假设 $ dm
是您的实体管理员。
Presuming that $dm
is your entity manager.
$qb = $dm->createQueryBuilder();
$qb->select($qb->expr()->count('u'))
->from('User', 'u')
->where('u.type = ?1')
->setParameter(1, 'employee');
$query = $qb->getQuery();
$usersCount = $query->getSingleScalarResult();
或者您也可以将其写在:
Or you could just write it in DQL:
$query = $dm->createQuery("SELECT COUNT(u) FROM User u WHERE u.type = ?1");
$query->setParameter(1, 'employee');
$usersCount = $query->getSingleScalarResult();
计数可能需要在id字段上,而不是对象,无法回忆起。如果是这样,只需将 COUNT(u)
或-> count('u')
更改为 COUNT(u.id)
或-> count('u.id')
或任何称为主键的字段。
The counts might need to be on the id field, rather than the object, can't recall. If so just change the COUNT(u)
or ->count('u')
to COUNT(u.id)
or ->count('u.id')
or whatever your primary key field is called.
这篇关于原则:用条件计算实体的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!