学说:用条件计算实体的项目
在 Doctrine 中,我如何计算一个实体的物品?例如,我意识到我可以使用:
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();
但这只会计算所有用户.我想只计算那些具有员工类型的人.我可以这样做:
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');
推荐答案
好吧,你可以使用 QueryBuilder 设置 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();
或者你可以把它写在 DQL:
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.
相关文章