php - Doctrine 中的分离实体错误

标签 php symfony doctrine

我正在将一组实体发布到 Controller ,我想删除所有这些实体。然而,下面的代码抛出一个 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();

最佳答案

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

合并应该像这样完成 $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

关于php - Doctrine 中的分离实体错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23459470/

相关文章:

php - Symfony/Doctrine/MongoDB 获取每 N 个项目

mysql - 从现有数据库生成具有点类型属性的实体

php - 如何使用 Doctrine 2 + Gedmo Translatable 将翻译存储在不同的表中

php - stmt bind_result() 不绑定(bind)所有列

mysql - Symfony 一对一关系 SQL 语法错误

php - 检查提交时表单值是否已更改

php - Symfony2 理解 Doctrine 查询加入

php - 部署到灵活的 PHP App Engine 时访问 Cloud SQL

php - 从数据库自引用表创建嵌套数组并显示在 Smarty 模板的嵌套列表中

php - 轻量级免费 PHP 文件管理器