Doctrine Insert in many-to-Many unidirectional relation

0

I have the following situation:

In my Location 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 Contact entity there is no mapping to Location. A place is always registered first, a contact is added to it later.

The problem is this: how to save this relationship? All the relationship I've seen use an attach () function, but I could not use it.

    
asked by anonymous 17.03.2015 / 15:14

1 answer

1

As far as I understand, you have a ManyToMany relation between Contato and Local entities, with only Local referencing the Contato entity (that is, it is a one-way relation).

In practice, each of your entities will initialize with an object of type when you have an object of type ArrayCollection , it is normal for Doctrine to generate methods get , set , add , and remove for that property. So your 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 get its $local variable (which has a ArrayCollection of contacts, even if empty) and add $contato to it by means of the Local::addContato(Contato $contato) method.

$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();
    
17.03.2015 / 15:42