Ada's order has three items: a coffee, a croissant, a tea. (The classes keep their French names, Commande for the order and LigneDeCommande for an order item, as in the French version of the exercise.) She adds an orange juice. The controller goes through a setter, added one day for a form:
$juice = (new LigneDeCommande('Orange juice', 1, 400))->setOrder($order); $order->setItems([...$order->getItems(), $juice]); $entityManager->flush();
The three existing items are in the array, along with the juice. Yet after flush(), only the juice is left in the database. The queries sent:
DELETE FROM order_item WHERE order_id = ? INSERT INTO order_item (product, quantity, unit_price, free, order_id) VALUES (?, ?, ?, ?, ?)
The relation is declared with orphanRemoval: true, and rightly so: an item removed from its order must disappear. But setItems() doesn't remove an item, it replaces the collection Doctrine was tracking with a new object. Doctrine concludes that the old one was emptied, and deletes all its items in one query. That DELETE runs before the juice's INSERT, so the juice is the only one left.
It is one of the costliest bugs around relations: it throws no error, and it erases data.
Your task
The /orders preview adds the juice to Ada's order, then shows the items in the database with their id.
- Replace
Commande::setItems()with anaddItem()method that modifies the collection in place and sets the item's order. - Make the controller use
addItem().
Ada's three items must stay the same: same ids, none recreated.