Doctrine relations in Symfony: ManyToOne and OneToMany
A Doctrine relation links two Symfony entities: ManyToOne on the owning side, which holds the foreign key, OneToMany on the inverse side, to navigate.
// Plat (dish): the owning side, which holds categorie_id. #[ORM\ManyToOne(inversedBy: 'plats')] #[ORM\JoinColumn(nullable: false)] private ?Categorie $categorie = null; // Categorie: the inverse side. /** @var Collection<int, Plat> */ #[ORM\OneToMany(targetEntity: Plat::class, mappedBy: 'categorie')] #[ORM\OrderBy(['prix' => 'ASC'])] private Collection $plats;
Only the owning side counts for the database: Doctrine reads $plat->getCategorie() to write categorie_id. The inverse side, declared with mappedBy, exists to loop over categorie.plats in a template, sorted by #[ORM\OrderBy]. inversedBy and mappedBy answer each other with the name of the property on the other side, and JoinColumn(nullable: false) makes the relation mandatory. The trap: adding an object to the inverse collection only. Nothing is saved, since Doctrine doesn't look at that side; that's why addPlat() also calls setCategorie(). An inversedBy pointing to a property that doesn't exist doesn't necessarily break the page, but doctrine:schema:validate reports it.
The exercises have you map the category and link it to the dishes, to sort the tavern's menu by category from cheapest to most expensive, then show the guestbook reviews under each dish, every new review being created already attached to its dish before the form is filled in.
8 exercises work on this concept, by writing code in the browser.
In the tracks
- A place for every dish Symfony for PHP developers · chapter 2: The cellar and the pantry
- The guestbook Symfony for PHP developers · chapter 3: The tavern's 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.
- 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.
- Never replace a Doctrine collection With orphanRemoval, a setItems() that replaces the collection wipes every item in the database, even the ones passed back to it. An adder keeps them.
- Deleting an item removed from its order Removing an item from the collection doesn't delete it: orphanRemoval tells Doctrine that an item without an order has no reason to exist.
- Saving an order with its items “A new entity was found through the relationship”: with cascade: ['persist'], a single persist() saves the order and its items.
- Keeping both sides of a OneToMany relation in sync Adding an item to an order's collection doesn't save it: Doctrine only reads the owning side, the ManyToOne.