N+1 queries with Doctrine: spotting and avoiding them
N+1 queries with Doctrine: one query for the list, then one more per item as soon as a loop walks through a lazily loaded relation.
// In CategorieRepository: the whole menu, dishes and ingredients included, in one query. return $this->createQueryBuilder('c') ->leftJoin('c.plats', 'p') ->addSelect('p') ->leftJoin('p.ingredients', 'i') ->addSelect('i') ->orderBy('c.position', 'ASC') ->getQuery() ->getResult();
Doctrine loads relations lazily: as long as you don't loop over $categorie->getPlats(), nothing hits the database; on the first loop, a query goes out, and a loop sends as many as it has items. Nothing breaks, the page stays correct, it just gets slower as the data grows. The usual fix is the join above, leftJoin() followed by addSelect(), which brings back the list and its relations in one go. The trap: a join without addSelect() filters but hydrates nothing, and the queries come back; an innerJoin() drops the items that have no relation.
In the tavern, an SQL query counter at the bottom of each page acts as a witness: the exercises have you load the whole menu in one query, track down a regression that raises no error, and keep a new page within a query budget.
5 exercises work on this concept, by writing code in the browser.
In the tracks
- The Friday rush Symfony for PHP developers · chapter 8: Back to the cellar
- 🐉 Boss: the collapsed storeroom Symfony for PHP developers · chapter 8: Back to the cellar
- The story night poster Symfony for PHP developers · chapter 12: The big night
In Practice
- Filtering without truncating collections A WHERE on a join loaded with addSelect() leaves collections incomplete, and they stay that way in the EntityManager. EXISTS filters without cutting anything.
- 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
PaginationDoctrineRelationsDebuggingMigrationsManyToManyFormsSecurity