Detached entity error in Doctrine

2020-06-13 02:42发布

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条回答
甜甜的少女心
2楼-- · 2020-06-13 03:35

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.

JPA state transitions

查看更多
登录 后发表回答