原则中的分离实体错误 [英] Detached entity error in Doctrine

查看:42
本文介绍了原则中的分离实体错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一系列实体发布到控制器,我希望将其全部删除。但是,以下代码引发在删除MyProject\Bundle\MyBundle\Entity\MyEntity @ 000000004249c13f00000001720a4b59 错误期间发现了分离的实体。我在哪里错了?

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();


推荐答案

您应使用 merge 对处于分离状态的实体进行操作,并且您要将其置于托管状态。

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

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

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();

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

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();

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

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.

这篇关于原则中的分离实体错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆