A have a code like this:
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery("SELECT p FROM AcmeBlogBundle:Publish p
ORDER BY p.update_date DESC");
$query->setFirstResult(($page-1)*$ads_on_page);
$query->setMaxResults($ads_on_page);
$posts = $query->getResult();
Now I am trying to get the total number of rows in the query (not depending on setMeaResult course).
I tried to use count() function but it doesn works…
So I did SELECT p, count(p.id) as p_count FROM AcmeBlogBundle:Publish p ORDER BY update_date DESC and it works, but I see that now I have only one row [I think that it because count() return only one row]. So I did two queries, like this:
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery("SELECT p FROM AcmeBlogBundle:Publish p
ORDER BY p.update_date DESC");
$query->setFirstResult(($page-1)*$posts_on_page);
$query->setMaxResults($posts_on_page);
$count_query = $em->createQuery("SELECT COUNT(p.id) AS p_count FROM AcmeBlogBundle:Publish p
ORDER BY p.update_date DESC");
$posts = $query->getResult();
$count = $count_query->getResult();
It works well, but I would like to know is it the right way?
Yes, it is. The first query will get only the number of records up to the number that is set with
setMaxResults. The second query will count how many records a query may return. There’s no another way to do two different things.PS: If you want to build pagination, consider using DoctrineExtensions. It will let you write a query only once (but it still does two queries underneath).