Doctrine: Counting an entity's items with a condition

前端 未结 3 1329
说谎
说谎 2021-02-02 10:37

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()         


        
3条回答
  •  攒了一身酷
    2021-02-02 11:35

    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 :

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

提交回复
热议问题