学说:用条件计算实体的项目 [英] Doctrine: Counting an entity's items with a condition

查看:16
本文介绍了学说:用条件计算实体的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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.

这篇关于学说:用条件计算实体的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆