Search code examples
symfonydoctrine-ormsymfony-2.4

Persist object within entity


My problem is very simple !

2 entities :

/**
 * @ORM\Entity
 * @ORM\Table(name="tournament")
 */
class Tournament
{
    …
    …
    …

    /**
     * @ORM\OneToMany(targetEntity="Siriru\GSBundle\Entity\Match", mappedBy="tournament")
     */

    …

    protected $matches;

    public function start()
    {
        $this->addMatch(new Match());
    }
}

and

/**
 * @ORM\Entity
 * @ORM\Table(name="match")
 */
class Match
{

    /**
     * @ORM\ManyToOne(targetEntity="Siriru\GSBundle\Entity\Tournament", inversedBy="matches")
     * @ORM\JoinColumn(nullable=false)
     */
    protected $tournament;
}

I need to persist the new Match I created with the start() function. Is it possible ? Or maybe it's a very bad way to do it.

Thanks !!

Siriru


Solution

  • Add: cascade={"persist"} to options on your $matches property in Tournament class. Now when you do:

    $myTournament->start();
    $em->persist($myTournament);
    $em->flush();
    

    Match record will be created in DB automatically by Doctrine.