Detached entity error in Doctrine

2020-06-13 02:50发布

问题:

I am posting an array of entities to a controller, all of which I'd like to delete. However, the below code throws an A detached entity was found during removed MyProject\Bundle\MyBundle\Entity\MyEntity@000000004249c13f00000001720a4b59 error. Where am I going wrong?

$doctrineManager = $this->getDoctrine()->getManager();
foreach ($form->getData()->getEntities() as $entity) {
    $doctrineManager->merge($entity);  
    $doctrineManager->remove($entity);
}
$doctrineManager->flush();

回答1:

You should use merge operation on entities which are in detached state and you want to put them to managed state.

Merging should be done like this $entity = $em->merge($detachedEntity). After that $entity refers to the fully managed copy returned by the merge operation. Therefore if your $form contains detached entities, you should adjust your code like this:

$doctrineManager = $this->getDoctrine()->getManager();
foreach ($form->getData()->getEntities() as $detachedEntity) {
    $entity = $doctrineManager->merge($detachedEntity);  
    $doctrineManager->remove($entity);
}
$doctrineManager->flush();

However, in case that the $form does not contain detached entities, you should remove the merge operation, like this:

$doctrineManager = $this->getDoctrine()->getManager();
foreach ($form->getData()->getEntities() as $entity) {
    $doctrineManager->remove($entity);
}
$doctrineManager->flush();

This image should help you to understand entity state transitions. It is taken from Java Persistence API, but in Doctrine2 it is about the same.