Symfony Published on

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.

Topics covered: DoctrineRelationsOneToMany

Grace orders at the counter: two coffees, a croissant, an orange juice. (The classes keep their French names, Commande for the order and LigneDeCommande for an order item, as in the French version of the exercise.) The order is entered in one go, with its items, then the controller saves it:

$order = (new Commande('Grace'))
    ->addItem(new LigneDeCommande('Coffee', 2, 250))
    ->addItem(new LigneDeCommande('Croissant', 1, 150));

$entityManager->persist($order);
$entityManager->flush();

addItem() does keep both sides of the relation in sync. Yet Doctrine refuses:

A new entity was found through the relationship 'App\Entity\Commande#items' that was not
configured to cascade persist operations for entity: App\Entity\LigneDeCommande@…

Doctrine only persists what it is given. Walking the order's collection, it finds items it doesn't know, and its message suggests two fixes: call persist() on each item, or declare that persist cascades from the order to its items.

The choice is not a matter of taste. Cascading suits an aggregate: a group of objects saved together, because the children don't exist without their parent. An order and its items are a textbook example.

Your task

The /orders/new preview saves Grace's order, then reads it back from the database.

  1. Make persist() on an order save its items too.
  2. Only cascade persist: nothing else is needed here.

The controller doesn't change.