我将一组实体发布到控制器,我想删除所有这些实体。但是,以下代码会引发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();
答案 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中它大致相同。