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

In Practice

Related concepts

DoctrineOneToManyN+1 queriesFormsQueryBuilderPagination