ManyToMany with Doctrine: owning side and inverse side
A ManyToMany relation with Doctrine links two Symfony entities both ways, through a join table that stores one row per pair.
// Plat (dish): the owning side, the one Doctrine saves (plat_ingredient table). #[ORM\ManyToMany(targetEntity: Ingredient::class, inversedBy: 'plats')] #[ORM\OrderBy(['nom' => 'ASC'])] private Collection $ingredients; // Ingredient: the inverse side, used to navigate. #[ORM\ManyToMany(targetEntity: Plat::class, mappedBy: 'ingredients')] private Collection $plats; public function addPlat(Plat $plat): static { if (!$this->plats->contains($plat)) { $this->plats->add($plat); $plat->addIngredient($this); // otherwise, nothing reaches the database } return $this; }
A dish contains several ingredients, an ingredient goes into several dishes: neither table can hold the foreign key, hence the join table, created by the migration. The side that declares inversedBy is the owner, the one that declares mappedBy is the inverse, and #[ORM\OrderBy] sorts the collection when it loads. The trap: Doctrine only writes to the database what the owning side contains. An addPlat() method that only fills the inverse collection gives PHP objects that look up to date, a flush() without error, and an empty join table.
The exercises have you link the tavern's dishes to their ingredients, sorted alphabetically and shown on each dish's page, then find out why, after Pipin tidied up the cellar, not a single ingredient shows up any more.
2 exercises work on this concept, by writing code in the browser.
In the tracks
- The pantry Symfony for PHP developers · chapter 8: Back to the cellar
- 🐉 Boss: the collapsed storeroom Symfony for PHP developers · chapter 8: Back to the cellar