Viktor Sydorenko
Viktor Sydorenko

Reputation: 683

Save new Entity with relations on existed Entity (Symfony/Doctrine2)

I want to create new Entity SlideTranslation, and assign existed slide. But every time entity had created without id of Slide. I can create SlideTranslation and than assign Slide to it, but it seems bad solution for me.

$slide = $em->getRepository('Model:Slide')->find($id);

if(isset($slide)) {
    try {
        $slideTranslation = new SlideTranslation();
        $slideTranslation->setTranstable($slide);
        $slideTranslation->setLocale('uk');
        $slideTranslation->setAltText('Alt text');
        $em->persist($slideTranslation);
        $em->flush();
    } catch (Exception $e) {
        dump($e->getMessage());
    }
}

Relations.

/**
 * @ORM\ManyToOne(targetEntity="Model\Entity\Slide", inversedBy="tranlations")
 * @ORM\JoinColumn(name="translatable_id", referencedColumnName="id")
 */
private $transtable;

I have tried method with getReference, but no result. Maybe I am breaking some patterns or principles and It's not possible in Doctrine2.

Upvotes: 0

Views: 99

Answers (1)

Fernando Caraballo
Fernando Caraballo

Reputation: 583

You will have to probably do it in the other way around

$slide = $em->getRepository('Model:Slide')->find($id);

$slideTranslation = new SlideTranslation();
$slideTranslation->setLocale('uk');
$slideTranslation->setAltText('Alt text');

$slide->addTranslation($slideTranslation);

$em->flush();

Then add cascade to the Slide entity, and you don't even need to persist the entity Translation

/**
 * @ORM\OneToMany(targetEntity="Model\Entity\SlideTranslation", mappedBy="transtable", cascade={"persist", "remove"})
 */
 private $translations;

Upvotes: 1

Related Questions