3

I want to get count of all records in DB. I haven't found one recommended way to do this. So I've built in my entity repo this function:

public function countAll()
{
    return $this->createQueryBuilder('post')
        ->select('COUNT(post)')
        ->getQuery()->getSingleScalarResult()
        ;
}

and it's OK, because it returns me count of all items. I use FOSRestBundle, so my action in controller looks like:

public function getPostsCountAction() {
    return $this->em->getRepository('KamilTestBundle:Post')->countAll();
}

and result at the addres posts/count.json looks like:

"16"

But... I want to take this value as integer. I don't know why QueryBuilder returns it as string. Even if I use ->getQuery()->getResult() and dump this output it's also string, not integer.

How can I take this value as integer? It is possible?

Kamil P
  • 782
  • 1
  • 12
  • 29

2 Answers2

7

intval() will return the number representation of a string.

While it might be a slippery thing to use this, you should be 100% fine since you know you will be getting only numbers.

public function countAll()
{
    return intval($this->createQueryBuilder('post')
        ->select('COUNT(post)')
        ->getQuery()->getSingleScalarResult());
}
Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
Andrius
  • 5,934
  • 20
  • 28
  • Mhm, when I use "COUNT(post)" it always will be integer. But maybe I can do this with doctrine. For example: when I take complete entity id's of records are integers. – Kamil P Nov 10 '15 at 10:36
  • Doesn't my answer solve it? What other problems are you having? – Andrius Nov 10 '15 at 10:37
  • 3
    Or `return (int) $this->createQueryBuilder('post')....->getSingleScalarResult()`. – qooplmao Nov 10 '15 at 10:46
-3
return count($this->em->getRepository('KamilTestBundle:Post')->findAll());

This should return an integer (count).

An alternative could be typecasting:

 return (int) $this->em->getRepository('KamilTestBundle:Post')->countAll();

This will just convert your string to an int and should be more efficient than counting in PHP.

George Irimiciuc
  • 4,573
  • 8
  • 44
  • 88
  • 8
    Yes, but this solution isn't good idea. It's OK when i have 16 posts, but when it will be number like 16000? It doesn't make sense to take all posts and count it on PHP side. – Kamil P Nov 10 '15 at 10:34
  • True, but you didn't specify you have such a large number of entries. Lettings the db query count them is the better idea in this case. – George Irimiciuc Nov 10 '15 at 10:36
  • 1
    I don't know how many entities I will have in future :) I always prefer to count items with DB query. – Kamil P Nov 10 '15 at 10:40
  • 1
    Try typecasting as I suggested, see if it works. I don't understand why I am getting downvotes for a plausible answer. – George Irimiciuc Nov 10 '15 at 10:41