问题
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