Doctrine QueryBuilder: writing your own queries in Symfony
Doctrine's QueryBuilder builds custom DQL queries in PHP when findBy() is no longer enough: optional filters, chosen sorting, joins.
public function findAvecFiltre(FiltreCarte $filtre): array { $qb = $this->createQueryBuilder('p') ->orderBy('p.'.$filtre->tri->value, 'ASC'); // an enum: "prix" or "nom", nothing else if (null !== $filtre->prixMax) { $qb->andWhere('p.prix <= :prixMax')->setParameter('prixMax', $filtre->prixMax); } return $qb->getQuery()->getResult(); }
You call it from a repository with createQueryBuilder('p'), then chain where(), andWhere(), orderBy() and setParameter(). It produces DQL: you talk about entities and properties (p.prix), not tables and columns. Its point is to build a query piece by piece, adding a condition only if the filter is set. The classic trap: concatenating a value coming from the HTTP request into the DQL string. A value always goes through a parameter; a property name, which can't be a parameter, must come from a closed list, an enum for instance.
The exercises have you write the queries of the tavern's menu, from sorting by price to the dish that fits a budget, then an API filter where every criterion is optional.
3 exercises work on this concept, by writing code in the browser.
In the tracks
- A tailor-made query Symfony for PHP developers · chapter 2: The cellar and the pantry
- Filtering the menu Symfony for PHP developers · chapter 5: Magic scrolls
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.