Symfony2删除并保存多对多关系 [英] Symfony2 remove and save many to many relations
问题描述
我今天需要你的帮助.我正在使用Symfony 2.1开发一个小型应用程序,但是我有一个基本问题,我必须使用具有多对多关系的表来创建第三个表:
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; }
和:
/**
* @ORM\ManyToMany(targetEntity="Alood\BackBundle\Entity\Usuario", mappedBy="alergenos")
**/
protected $usuarios;
然后我需要删除未选择的Alergenos,这是我的控制器:
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!
推荐答案
要从集合中删除项目,请使用以下命令:
In order to remove an item from a collection use the following:
$collection->removeElement($item);
remove($key)
函数将按键删除,而removeElement($item)
将从集合中删除该项目(如果找到).在 ArrayCollection代码此处.
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.
这篇关于Symfony2删除并保存多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!