I have a bidirectional many-to-one relationship. Let's go with Foo
and Bar
. Foo
has the following:
class Foo
{
/**
* @ORM\OneToMany(targetEntity="Bar", mappedBy="foo", cascade={"all"}, orphanRemoval=true)
*/
private $bars;
public function __construct()
{
$this->bars = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* @param mixed $bars
*/
public function setBars($bars)
{
$this->bars = $bars;
}
/**
* @param Bar $bar
*/
public function addBar(Bar $bar)
{
$this->bars->add($bar);
}
/**
* @return mixed
*/
public function getBars()
{
return $this->bars;
}
}
And Bar
:
class Bar
{
/**
* @ORM\Id()
* @ORM\ManyToOne(targetEntity="Foo", inversedBy="bars")
* @ORM\JoinColumn(name="foo_id", referencedColumnName="id", nullable=false)
*/
protected $foo;
/**
* @param Foo $foo
*/
public function setFoo(Foo $foo)
{
$this->foo = $foo;
}
/**
* @return Foo
*/
public function getFoo()
{
return $this->foo;
}
}
Okay, so with the classes above, when I write:
$foo = new Foo();
$bar1 = new Bar();
$bar2 = new Bar();
$foo->addBar($bar1);
$foo->addBar($bar2);
And try to persist, I get an error about how each Bar
's foo property is null:
Similarly, if I flip it around to:
$foo = new Foo();
$bar1 = new Bar();
$bar2 = new Bar();
$bar1->setFoo($foo);
$bar2->setFoo($foo);
I can persist, but then my Foo
s newly generated PersistentCollection
for that property is empty:
Is this intended behavior? I'm used to other ORMs on different platforms wiring up the bidirectional relationship upon assignment, so I'm not sure if this is normal for Doctrine/PHP, or if my annotations are messed up (which the error message above leads me to believe).
So, any help would be greatly appreciated.