Dawid Pura
Dawid Pura

Reputation: 1029

Doctrine 2: OneToMany relation

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

Here is the problem with taking into ArrayCollection $secondList elements from Second class. Second ManyToOne relation is working properly. Perhaps I did something wrong in initializing a persistance (because First_Id in SQL base is null always).

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

Any suggestions?

Upvotes: 2

Views: 363

Answers (2)

Ivan Pintar
Ivan Pintar

Reputation: 1881

Doctrine2 docs say this:

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

This means that you'll have to do something like:

$second->setParent($first); 

As $second table has the foreign key. Or you could add a cascade={"persist"} option to the$first->secondList property.

Upvotes: 1

mbinette
mbinette

Reputation: 5094

You should make sure you close your parenthesis in the First class.

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

If that is not the problem - is there any error message ?

Upvotes: 1

Related Questions