如何在不删除任何内容的情况下取消多对多表中的关系链接?
我试过了:
$getProject = $this->_helper->getDocRepo('Entities\Project')->findOneBy(array('id' => $projectId));
$getCat = $this->_doctrine->getReference('\Entities\Projectcat', $catId);
$getProject->getCategory()->removeElement($getCat);
$this->em->flush();
我的Projectcat实体:
/**
* @ManyToMany(targetEntity="\Entities\Projectcat", cascade={"persist", "remove"})
* @JoinColumn(name="id", referencedColumnName="id")
*/
protected $getCategory;
最佳答案
一个相当古老的帖子,但想提供一种方法来确保从ORM实体方面删除该关联,而不是必须手动执行每个实体的集合removeElement并通过@Rene Terstegen扩展答案。
问题在于,Doctrine不会“自动”关联关联,但是您可以更新实体的“添加/删除”方法来关联。
https://gist.github.com/Ocramius/3121916
以下示例基于OP的项目/类别架构。
假定表project_category
是ManyToMany
关系表,并且project
和category
表使用主键id
。
class Project
{
/**
* @ORM\ManyToMany(targetEntity="Category", inversedBy="projects")
* @ORM\JoinTable(
* name="project_category",
* joinColumns={
* @ORM\JoinColumn(name="project", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="category", referencedColumnName="id")
* }
* )
*/
protected $categories;
public function __construct()
{
$this->categories = new ArrayCollection();
}
/**
* @param Category $category
*/
public function removeCategory(Category $category)
{
if (!$this->categories->contains($category)) {
return;
}
$this->categories->removeElement($category);
$category->removeProject($this);
}
}
class Category
{
/**
* @ORM\ManyToMany(targetEntity="Project", mappedBy="categories")
*/
protected $projects;
public function __construct()
{
$this->projects = new ArrayCollection();
}
/**
* @param Project $project
*/
public function removeProject(Project $project)
{
if (!$this->projects->contains($project)) {
return;
}
$this->projects->removeElement($project);
$project->removeCategory($this);
}
}
然后,您要做的就是调用
removeCategory
或removeProject
方法,而不是两者。同样的方法也可以应用于addCategory
和addProject
方法。$project = $em->find('Entities\Project', $projectId);
$category = $em->getReference('Entities\Category', $categoryId);
$project->removeCategory($category);
$em->flush();
关于 Doctrine 2,如何消除多对多的联想?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7299508/