Doctrine中的分离实体错误

时间:2014-05-04 17:43:06

标签: php symfony doctrine

我将一组实体发布到控制器,我想删除所有这些实体。但是,以下代码会引发A detached entity was found during removed MyProject\Bundle\MyBundle\Entity\MyEntity@000000004249c13f00000001720a4b59错误。我哪里错了?

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

1 个答案:

答案 0 :(得分:25)

您应该对处于分离状态的实体使用 merge 操作,并且您希望将它们置于托管状态。

合并应该像这样$entity = $em->merge($detachedEntity)完成。之后$entity引用合并操作返回的完全托管副本。因此,如果您的$form包含分离的实体,则应该像这样调整代码:

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

但是,如果$form不包含分离的实体,则应删除 merge 操作,如下所示:

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

此图像应该可以帮助您了解实体状态转换。它取自Java Persistence API,但在Doctrine2中它大致相同。

JPA state transitions