How to page Doctrine2 results [closed]
Want to improve this question? Update the quest开发者_开发技巧ion so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this questionI cant find Doctrine_Pager in Doctrine2 and really need a way to page my query results. Is there a way to use some alternative pager (Pear, Zend)? Please post some example code as well if solution is available. Google didnt helped me, so hope folks will :)
I wrote this extension for Doctrine2 that contains a powerful pager:
http://github.com/beberlei/DoctrineExtensions
In Doctrine 2.2, there is a Paginator helper class: http://docs.doctrine-project.org/en/latest/tutorials/pagination.html
Very easy to use :)
use Doctrine\ORM\Tools\Pagination\Paginator;
$dql = "SELECT p, c FROM BlogPost p JOIN p.comments c";
//build the query for the page you want to display
$query = $entityManager->createQuery($dql)
->setFirstResult(0)
->setMaxResults(10);
$paginator = new Paginator($query, $fetchJoinCollection = true);
$c = count($paginator); //automatically makes another query and returns the total number of elements.
//iterating over the paginator iterates over the current page
foreach ($paginator as $post) {
echo $post->getHeadline() . "\n";
}
PagerFanta, as mentioned by Maksim, comes recommended. However, there is also one other pagination bundle that should at least be mentioned: http://symfony2bundles.org/knplabs/KnpPaginatorBundle
Unlike PagerFanta, KnpPaginatorBundle currently requires the zend paginator package as a dependency.
Just as a note though, Query#setMaxResults / Query#setFirstResult covers most of the basic needs for paging.
There is a good 3rd one solution: https://github.com/whiteoctober/Pagerfanta
I found it very useful
精彩评论