/** @Entity */
class First
{
/** @OneToMany(targetEntity="Second", mappedBy="parent") */
protected $secondList;
// access methods here
public function __construct()
{
$this->secondList = new ArrayCollection();
}
}
/** @Entity */
class Second
{
/**
* @ManyToOne(targetEntity="First", inversedBy="secondList")
* @JoinColumn(name="First_id", referencedColumnName="Id")
*/
protected $parent;
}
这是从 Second
类中获取 ArrayCollection $secondList
元素时出现的问题。 第二
ManyToOne 关系工作正常。也许我在初始化持久性时做错了什么(因为 SQL 库中的 First_Id
始终为 null
)。
$first = new Second();
$second = new First();
$first->getSecond()->add($second);
$em->persist($second);
$em->persist($first);
有什么建议吗?
最佳答案
Doctrine2 docs说这个:
In the case of bi-directional associations you have to update the fields on both sides:
这意味着您必须执行以下操作:
$second->setParent($first);
由于$second
table具有外键。
或者,您可以向 $first->secondList
属性添加 cascade={"persist"}
选项。
关于php - 教义2 : OneToMany relation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12550230/