我有一個雙向的多對一關係。我們來用Foo
和Bar
。 Foo
有以下幾點:Doctrine 2 ArrayCollections - 我錯過了什麼?
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;
}
}
而且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;
}
}
好了,上面的班,當我寫:
$foo = new Foo();
$bar1 = new Bar();
$bar2 = new Bar();
$foo->addBar($bar1);
$foo->addBar($bar2);
並嘗試堅持,我得到一個錯誤關於每個Bar
的foo屬性如何爲空:
同樣,如果我周圍扳起:
$foo = new Foo();
$bar1 = new Bar();
$bar2 = new Bar();
$bar1->setFoo($foo);
$bar2->setFoo($foo);
我能堅持,但後來我Foo
新近產生PersistentCollection
該屬性是空的:
這是有意的行爲?我習慣了不同平臺上的其他ORM在分配時接合雙向關係,所以我不確定這對於Doctrine/PHP是否正常,或者我的註釋混亂了(上面的錯誤消息讓我相信)。
所以,任何幫助將不勝感激。
你試圖堅持美孚你打電話之前setFoo? – Alex
沒有變化。 'PersistentCollection'仍爲空 –