1

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?

3 Answers 3

1

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).

Sign up to request clarification or add additional context in comments.

Comments

0

Doctrine 2.2 includes a pagination class that should solve the problem: http://docs.doctrine-project.org/en/latest/tutorials/pagination.html

Comments

0

setMaxResults not working on OneToMany

Example use a subquery, join many linked entities, use setMaxResults... You'll get a limit for the whole query...

So if you want 2 articles, you fetch all their comments. Using setMaxResults 2

You'll have the first article with 2 comments.

This feature is not smart to be polite.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.