Doctrine: Counting an entity's items with a condition

前端 未结 3 1328
说谎
说谎 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:30

    Well, you could use the QueryBuilder to setup a COUNT query:

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

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

    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.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-02-02 11:35

    Since doctrine 2.6 you can just count the result of the provided conditions when you don't really need the data:

    $usersCount = $dm->getRepository('User')->count(array('type' => 'employee'));
    

    Upgrade to 2.6

    0 讨论(0)
提交回复
热议问题