简体   繁体   中英

Doctrine - count users in table by id

I have 6 records in a database. 3 from user 1, 2 from user 2 and 1 from user 3.

I want to count them by user_id so the final result would be 3. And it always returns count of all records from table. It returns 6.

My func:

return $this->getDeviceRepository()
        ->createQueryBuilder('tlu')
        ->select('COUNT(tlu.user_id)')
        ->getQuery()
        ->getResult();

You have 2 solutions (with groupBy or countDistinct)

return $this->getDeviceRepository()
        ->createQueryBuilder('tlu')
        ->select('COUNT(tlu.user_id)')
        ->groupBy('tlu.user_id')
        ->getQuery()
        ->getResult();

or

return $this->getDeviceRepository()
        ->createQueryBuilder('tlu')
        ->select('COUNT(tlu.user_id)')
        ->countDistinct('tlu.user_id')
        ->getQuery()
        ->getResult();

Yes, we can do as following

getResult()->count();

or

return $this->getDeviceRepository()
        ->createQueryBuilder('tlu')
        ->select('COUNT(tlu.user_id)')
        ->countDistinct('tlu.user_id')
        ->getQuery()
        ->getSingleScalarResult();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM