Doctrine cascade on OneToMany does not set the parent object?

…衆ロ難τιáo~ 提交于 2019-12-24 23:45:04

问题


I have a User objects which has many Journal entries.

The user class contains a $userJournals property and the required add/remove functions, as below:

class User{
   ....
   /**
   * @var \Doctrine\Common\Collections\ArrayCollection
   *
   * @ORM\OneToMany(targetEntity="models\UserJournal", mappedBy="user", cascade={"persist"})
   */
   protected $userJournals;
   ....

   public function addUserJournal(\models\UserJournal $userJournal)
   {
          $this->userJournals->add($userJournal);
          return $this;
   }
 }

The UserJournal class contains the User object, and a getter/setter for it. The annotation for the $user is here:

   class UserJournal
   {
   /**
   * @var models\User
   *
   * @ORM\ManyToOne(targetEntity="models\User", inversedBy="userJournals", cascade={"persist"})
   * @ORM\JoinColumns({
   *   @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
   * })
   */
   protected $user;
}

My understanding is that cascade persist makes it so I do not have to set the User on the UserJournal, I can just add the UserJournal to the User, save the User, and it will work.

    $user = $this->getRepository('User')->find(1);

    $userJournal = new models\UserJournal();
    $userJournal->setText('testCode');
    $user->addUserJournal($userJournal);
    $em->persist($user);
    $em->flush();

However, this code produces a SQL error that user_id cannot be null on the UserJournal.

Isn't there a way to do this without having to do $userJournal->setUser($user); in this code or in the addUserJournal() function?

来源:https://stackoverflow.com/questions/19865955/doctrine-cascade-on-onetomany-does-not-set-the-parent-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!