Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Doctrine get count all as integer

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?

like image 909
Kamil P Avatar asked Mar 09 '26 06:03

Kamil P


1 Answers

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());
}
like image 53
Andrius Avatar answered Mar 11 '26 19:03

Andrius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!