Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

symfony - Doctrine "A new entity was found through the relationship" error

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.

I have a OneToMany Bi-Directional relationship as follow:

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;
}

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: A new entity was found through the relationship 'CompanyMyBundleEntityStep#channel' that was not configured to cascade persist operations for entity

why is it even finding new relationships from the inverse side? Here's my code:

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

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.

Possible solutions:

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

  • Persist explicitly both entities:

    $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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...