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