2012-09-23 110 views
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; 
} 

下面是从Second类考虑ArrayCollection $secondList元素的问题。 Second ManyToOne关系正常工作。也许我在初始化持久性方面做了错误(因为SQL基础中的First_Id始终是null)。学说2:一对多关系

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

有什么建议吗?

回答

1

Doctrine2 docs这样说:

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

这意味着你必须做一些事情,如:

$second->setParent($first); 

由于$second有外键。 或者您可以将cascade={"persist"}选项添加到$first->secondList属性。

+0

好吧,这真的帮助我设置第二个表记录中的First_Id列。但是,试图获取First类对象并不会将Second取到“ArrayCollection”。我只有空集合:| –

+0

所以在数据库中一切都很好?你如何获取这些东西?你如何检查你有什么?因为当你调用$ first-> getSecond()时,它应该加载它。 – Pinetree

+0

事实上,这就是我要做的。 DB是好的(最终模式是由doctrine tool-kit创建的)。我使用来自'EntityManager'类的find()或getRepository()方法获取对象。对象被正确创建,即使我只有'Second'类对象,我与'First'相关的类对象有充分的关系。噢,我用'serialize($ first-> getSecondList() - > current())'检查这个列表,'$ takedSecond-> getSomeOtherValue()'显示错误在非对象变量上使用方法。 –

1

您应该确保在第一课中关闭括号。

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

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

+0

哦,台风。没有错误消息,但如果我尝试坚持第一类对象之前第二有关于使用级联映射的错误(某些属性,我还没有找到关于必要使用的教义引用)。 –

+0

尝试将此添加到您的OneToMany关系(针对级联错误):'cascade = {“persist”}我不完全确定其他问题是什么......是否所有内容都保存到数据库中? – mbinette