Doctrine 中的分离实体错误

Detached entity error in Doctrine(Doctrine 中的分离实体错误)
本文介绍了Doctrine 中的分离实体错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一组实体发布到控制器,我想删除所有这些实体.但是,下面的代码会引发 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 中的分离实体错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)