0

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();
Elementor
  • 57
  • 7
  • Does this answer your question? [Get maximum id inside Doctrine entity](https://stackoverflow.com/questions/36937754/get-maximum-id-inside-doctrine-entity) – yivi Nov 20 '19 at 12:45

2 Answers2

2

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();
Rached BCH
  • 31
  • 2
0

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();
Rached BCH
  • 31
  • 2