Set Limit When Using createQuery in Symfony 2.0

Author: Mic Johnson
Last Edited: 04/22/2012
Category: Symfony2.0

Tags: createQuery, limit, symfony2, symfony 2.0, setmaxresults, entity manager,

To set the limit when using entitymanager->createQuery() is easy. Instead of trying to use something to the effect of "LIMIT 0,1000" on the end of your query, try ->setMaxResults(1000) on your query object.

$em = $this->getDoctrine()->getEntityManager();
$pages = $em->createQuery("SELECT p FROM MicJohnson\PageBundle\Entity\Page p WHERE p.id > :id")
            ->setParameter('id', 0)
            ->setMaxResults(10)
            ->getResult();