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();