Doctrine Insert regarding Many-to-Many unidirectional

Asked

Viewed 237 times

0

I have the following situation:

In my Local entity:

 /**
 * @ORM\ManyToMany(targetEntity="Contato")
 * @ORM\JoinTable(name="contato_localidade",
 *      joinColumns={@ORM\JoinColumn(name="localidade_id", referencedColumnName="identificador")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="contato_id", referencedColumnName="identificador")}
 *      )
 * */
protected $contatos;

In the entity Contact there is no mapping to Location. A site is always register first, a contact is added to it later.

The problem is, how to save this relationship? All the relationships I’ve seen use an attach() function, but I couldn’t use it.

1 answer

1


From what I understand, you have a relationship ManyToMany between entities Contato and Local, where only the entity Local reference to entity Contato (I mean, it’s a one-way relationship).

In practice, each of your entities will be initialized with a type object when you have a type object ArrayCollection, It is normal for Doctrine to generate methods get, set, add and remove for that property. So, their classes would look like this:

<?php

class Local
{
    private $contatos;

    public function __construct()
    {
        $this->contatos = new ArrayCollection();
    }

    public funcion addContato(Contato $contato)
    {
        $this->contatos->add($contato);
    }

    public function removeContato(Contato $contato)
    {
        $this->contatos->remove($contato);
    }

    public function getContatos()
    {
        return $this->contatos;
    }

    public function setContatos($contatos)
    {
        $this->contatos = $contatos;

        return $this;
    }
}

and

<?php

class Contato
{
    private $locais;

    public function __construct()
    {
        $this->locais = new ArrayCollection();
    }

    public funcion addLocal(Local $local)
    {
        $this->locais->add($local);
    }

    public function removeLocal(Local $local)
    {
        $this->locais->remove($local);
    }

    public function getLocais()
    {
        return $this->locais;
    }

    public function setLocais($locais)
    {
        $this->locais = $locais;

        return $this;
    }
}

What you need to do later when adding a Contato to a Local, is to take your variable $local (who owns a ArrayCollection contacts, even if empty) and add a $contato to him by means of the method Local::addContato(Contato $contato).

$local = $this->getDoctrine()->getRepository('Local')->findOneById($localId);

$contato = new Contato();
$this->getDoctrine()->getManager()->persist($contato);

$local->addContato($contato);
$this->getDoctrine()->getManager()->persist($local);

$local->getDoctrine()->getManager()->flush();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.