Symfony Published on

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.

Topics covered: DoctrineRelationsOneToMany

An order has items: a OneToMany relation on the Commande side (the order), ManyToOne on the LigneDeCommande side (the order item). (The classes keep their French names, as in the French version of the exercise.) In the database, though, there is only one column, order_id, in the items table. So Doctrine distinguishes two sides:

  • the owning side, LigneDeCommande::$order (the ManyToOne, with inversedBy), which holds the column;
  • the inverse side, Commande::$items (the OneToMany, with mappedBy), which is there to navigate.

To write order_id, Doctrine only looks at the owning side. An item added to the collection alone goes to the database without an order:

$order->getItems()->add($item);
$entityManager->persist($item);
$entityManager->flush();
// NOT NULL constraint failed: order_item.order_id

Without nullable: false on the column, it would be worse: the item would be saved as an orphan, with no error at all.

Your task

At the counter, Ada ordered two croissants and a tea. The /orders preview adds two coffees with addItem(), saves, then reads her order back from the database. For now, saving fails.

  1. Fix Commande::addItem() so that the item knows its order.
  2. Make sure the same item added twice isn't duplicated.

The controller doesn't change: it is the entity's job to keep both sides in sync.