How to automatically remove orphans when merging a deserialized object graph in doctrine2?

I am using Symfony2 with Doctrine2 to create a backend API. This API will get the graph of objects in CRUD in the database.

I use the large JMSSerializer package to deserialize a json-encoded graph of objects into a separate graph of highlighted entitied, and then I would just like to merge this graph directly into a database.

In my code, I have 2 objects: parent and child. There is a OneToMany(cascade={"all"}, orphanRemoval=true) relation OneToMany(cascade={"all"}, orphanRemoval=true) defined in Parent.

In my database, I have a parent row with id of 1, which has 3 children with identifiers 1,2,3.

I would like to write something like (I do not use deserialization here to simplify the example):

 $parent = new Parent(); $parent->id = 1 // detached entity $existing_child = new Child(); $child->id = 2 // detached entity $new_child = new Child(); // new entity $parent->addChild($existing_child); $parent->addChild($new_child); $em = $this->getDoctrine() ->getEntityManager(); $em->merge($parent); $em->flush(); 

Thus, my new child is well created, and the existing child is updated, but old children (1 and 3) are not deleted.

Can someone help me if I missed something?

+6
source share

Source: https://habr.com/ru/post/918343/


All Articles