php Doctrine:根据条件计算实体的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19103699/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:50:46  来源:igfitidea点击:

Doctrine: Counting an entity's items with a condition

phpdoctrine-ormdoctrine

提问by luqita

How can I count an entity's items with a condition in Doctrine? For example, I realize that I can use:

如何在 Doctrine 中计算具有条件的实体的物品?例如,我意识到我可以使用:

$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');

采纳答案by Orbling

Well, you could use the QueryBuilderto setup a COUNTquery:

好吧,您可以使用QueryBuilder来设置COUNT查询:

Presuming that $dmis your entity manager.

假设那$dm是您的实体经理。

$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:

或者你可以用DQL编写它:

$query = $dm->createQuery("SELECT COUNT(u) FROM User u WHERE u.type = ?1");
$query->setParameter(1, 'employee');

$usersCount = $query->getSingleScalarResult();

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.

计数可能需要在 id 字段上,而不是在对象上,无法回忆。如果是这样,只需将COUNT(u)or更改->count('u')COUNT(u.id)or->count('u.id')或调用您的主键字段。

回答by Bacteries

This question is 3 years old but there is a way to keep the simplicity of the findBy() for count with criteria.

这个问题已经有 3 年历史了,但是有一种方法可以保持 findBy() 的简单性,以便根据条件进行计数。

On your repository you can add this method :

在您的存储库中,您可以添加此方法:

    public function countBy(array $criteria)
    {
        $persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName);
        return $persister->count($criteria);
    }

So your code will looks like this :

所以你的代码看起来像这样:

$criteria = ['type' => 'employee'];
$users = $repository->findBy($criteria, ['name' => 'ASC'], 0, 20);
$nbUsers = $repository->countBy($criteria);