教义“通过关系发现了一个新实体"错误 [英] Doctrine "A new entity was found through the relationship" error

查看:31
本文介绍了教义“通过关系发现了一个新实体"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我想说在发布这个问题之前,我已经阅读了所有文档并在谷歌上搜索了很多.我知道那个错误意味着什么(关系中的非持久实体)

First off I want to say I've read through all the docs and googled this plenty before posting this question. I know what that error means (un-persisted entity in a relationship)

我在我认为不应该收到此错误的地方收到此错误.

I'm getting this error where I think I shouldn't be getting it.

我的 OneToMany 双向关系如下:

Class Channel
{
    /** 
    * @ORMOneToMany(targetEntity="Step", mappedBy="channel", cascade={"all"}, orphanRemoval=true)
    * @ORMOrderBy({"sequence" = "ASC"})
    */
    protected $steps;
}

Class Step
{
    /** 
    * @ORMManyToOne(targetEntity="Channel", inversedBy="steps")
    */
    protected $channel;
}

一个Channel可以有多个Step,拥有方是Channel.从 Doctrine 2.4 升级到 2.5 后,我收到此错误:

One Channel can have many Steps and the owning side is Channel. After I upgraded from Doctrine 2.4 to 2.5 I'm getting this error:

DoctrineORMORMInvalidArgumentException: 发现一个新实体通过关系 'CompanyMyBundleEntityStep#channel'未配置为对实体进行级联持久化操作

DoctrineORMORMInvalidArgumentException: A new entity was found through the relationship 'CompanyMyBundleEntityStep#channel' that was not configured to cascade persist operations for entity

为什么它甚至从反面寻找新的关系?这是我的代码:

$channel = new Channel();
$step = new Step();
$channel->addStep($step);
$em->persist($channel);
$em->flush();

谢谢!

推荐答案

你是对的:Doctrine 只关注拥有方的变化,但你错了:你关系的拥有方是 Step,不是 Channel.

You're right: Doctrine looks only for changes into owning side but you're wrong: owning side of your relationship is Step, not Channel.

为什么 step 是拥有方?因为是具有外键的实体.甚至 Doctrine 文档也告诉你

Why is step the owning side? Because is the entity that has foreign key. Even Doctrine documentation says to you

拥有方必须使用 OneToOne 的 inversedBy 属性,ManyToOne 或 ManyToMany 映射声明.inversedBy 属性包含反面关联字段的名称.

The owning side has to use the inversedBy attribute of the OneToOne, ManyToOne, or ManyToMany mapping declaration. The inversedBy attribute contains the name of the association-field on the inverse-side.

可能的解决方案:

  • 尝试通过将 cascade={"all"} 放入 Step 实体来反转级联操作(您确定 all是正确的选择吗?)

    Possible solutions:

    • Try to invert cascade operations by putting cascade={"all"} into Step entity (are you sure that all is the correct choice?)

      明确保留两个实体:

      $channel = new Channel();
      $step = new Step();
      $channel->addStep($step);
      $em->persist($channel);
      $em->persist($step);
      $em->flush();
      

      这里阅读为什么这里提供的第二种方式也很好

      here you can read why second way provided here is fine too

      这篇关于教义“通过关系发现了一个新实体"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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