2
/** @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;
}

这是从类中获取ArrayCollection $secondList元素的问题。多对一关系工作正常。也许我在初始化持久性时做错了(因为在 SQL 基础中总是如此)。SecondSecondFirst_Idnull

$first = new Second();
$second = new First();
$first->getSecond()->add($second);
$em->persist($second);
$em->persist($first);

有什么建议么?

4

2 回答 2

1

您应该确保在 First class 中关闭括号。

/** @OneToMany(targetEntity =  "Second", mappedBy = "parent" ) */

如果这不是问题 - 是否有任何错误消息?

于 2012-09-23T06:35:43.560 回答
1

Doctrine2 文档这样说:

In the case of bi-directional associations you have to update the fields on both sides:

这意味着您必须执行以下操作:

$second->setParent($first); 

因为$second 有外键。或者,您可以cascade={"persist"}为该属性添加一个选项$first->secondList

于 2012-09-23T07:13:13.793 回答