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');
This question is 3 years old but there is a way to keep the simplicity of the findBy() for count with criteria.
On your repository you can add this method :
So your code will looks like this :
Well, you could use the QueryBuilder to setup a
COUNT
query:Presuming that
$dm
is your entity manager.Or you could just write it in DQL:
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')
toCOUNT(u.id)
or->count('u.id')
or whatever your primary key field is called.