Detached entity error in Doctrine

前端 未结 1 1238
独厮守ぢ
独厮守ぢ 2021-02-14 18:20

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

1条回答
  •  长情又很酷
    2021-02-14 18:55

    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

    0 讨论(0)
提交回复
热议问题