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

In Practice

Related concepts

PaginationDoctrineRelationsDebuggingMigrationsManyToManyFormsSecurity