3
votes
$cart = new Cart();
$item = new CartItem();

$variant = $repository->findOneById($variantId);

$item->setVariant($variant);
$cart->addItem($item);

$em->persist($cart);
$em->flush();

On flush() I got the following error:

A new entity was found through the relationship 'CartItem#variant' that was not configured to cascade persist operations for entity:
Variant@0000000034ce4ce4000000000391db0d. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). 
If you cannot find out which entity causes the problem implement 'Variant#__toString()' to get a clue.

Cart.xml

<one-to-many target-entity="CartItem" field="items" mapped-by="cart">
    <cascade>
        <cascade-persist/>
    </cascade>
</one-to-many>

CartItem.xml

<many-to-one field="cart" target-entity="Cart" inversed-by="items">
  <join-column name="cart_id" referenced-column-name="id" nullable="false" />
</many-to-one>
<many-to-one field="variant" target-entity="Variant">
    <join-column name="variant_id" referenced-column-name="id" nullable="false" />
</many-to-one>

In the Variant.xml I don't have CartItem mapping.

1
Do you have multiple entity managers? Specifically, is the variant repository using the same entity manager as the cart entities?Cerad
Yes, both entities use $em = $this->container->get('doctrine.orm.default_entity_manager');Ricardo Simas

1 Answers

1
votes

You need to persist both variant and item entities. You should also set the relationship on variant, not just item.