问题描述
我将一组实体发布到控制器,我想删除所有这些实体.但是,下面的代码会引发 A detached entity was found during removed MyProjectBundleMyBundleEntityMyEntity@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 MyProjectBundleMyBundleEntityMyEntity@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();
推荐答案
你应该对处于 detached 状态的实体使用 merge 操作并且你想把它们放到托管状态.
You should use merge operation on entities which are in detached state and you want to put them to managed state.
合并应该像这样$entity = $em->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
不包含 detached 实体,则应删除 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.
这篇关于Doctrine 中的分离实体错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!