Pagination with Doctrine: the Paginator in a Symfony repository
Pagination with Doctrine in Symfony asks the database only for the rows of one page, with LIMIT and OFFSET, then counts the total to place the page.
public function findPage(int $page, int $parPage): Paginator { $query = $this->createQueryBuilder('a') ->join('a.plat', 'p') ->addSelect('p') ->orderBy('a.creeLe', 'DESC') ->addOrderBy('a.id', 'DESC') ->setFirstResult(($page - 1) * $parPage) ->setMaxResults($parPage) ->getQuery(); return new Paginator($query, fetchJoinCollection: false); }
Loading fifty rows to show ten works, then collapses at fifty thousand. setFirstResult() and setMaxResults() turn the page into OFFSET and LIMIT; Doctrine's Paginator is iterated like the page, and count() runs a count query over the whole set, hence the number of pages. The second sort, on id, keeps the order stable when two rows share the same date: without it, a row can jump from one page to another. In the controller, #[MapQueryParameter] with min_range turns ?page=0 or ?page=abc into a 404. The trap: an offset written $page * $parPage instead of ($page - 1) * $parPage. The first page skips the ten most recent rows, and nothing breaks.
The exercises have you split the tavern's guestbook into pages of ten reviews, in three queries at most, with a 404 for pages that don't exist, then find out why travellers don't see the review they just wrote.
3 exercises work on this concept, by writing code in the browser.
In the tracks
- The big guestbook Symfony for PHP developers · chapter 8: Back to the cellar
- 🐉 Boss: the collapsed storeroom Symfony for PHP developers · chapter 8: Back to the cellar
In Practice
- Paginating orders loaded with their items On a query with a join, setMaxResults() limits SQL rows, not entities: Doctrine's Paginator pages through orders without cutting their collections.
Related concepts
N+1 queries#[MapQueryParameter]DebuggingMigrationsManyToManyDoctrineRelations