Search code examples
phpsymfonymany-to-manysymfony-2.1persist

Symfony2 remove and save many to many relations


I need your help today. I'm working on a small application using Symfony 2.1 but I have a base problem, I have to tables with a many to many relation which creates a third table:

class Usuario implements UserInterface {
/**
* @ORM\ManyToMany(targetEntity="Alood\BackBundle\Entity\Alergeno", inversedBy="usuarios")
* @ORM\JoinTable(name="UsuariosProductos",
 *      joinColumns={@ORM\JoinColumn(name="usuario_user", referencedColumnName="user")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="alergeno_id", referencedColumnName="id")}
 *      )
**/
protected $alergenos;
}


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

public function getAlergenos() { return $this->alergenos; }

and:

/**
* @ORM\ManyToMany(targetEntity="Alood\BackBundle\Entity\Usuario", mappedBy="alergenos")
**/
protected $usuarios;

Then I need to remove the non selected Alergenos, this is my controller:

$alergenosUser = $em->getRepository("BackBundle:Usuario")->find($usuario);

$resultSym = array_diff($alergenosUsuarioIds, $alergen);

foreach($resultSym as $result) {
    $alergenosUser->getAlergenos()->remove($result);
}
$em->persist($alergenosUser);
$em->flush();

Could you please help me to figure out what I'm doing wrong? Thanks you so much!


Solution

  • In order to remove an item from a collection use the following:

    $collection->removeElement($item);
    

    The remove($key) function will remove by key while removeElement($item) removes the item from the collection if found. Have a look at the ArrayCollection code here.

    Be aware that doctrine will only check the owning side of a relation for changes.