一个相当古老的帖子,但希望提供一种方法来确保关联已从教条的ORM实体一侧移除,而不是必须手动执行每个实体的集合removeElement并扩展@Rene Terstegen的答案。
的问题是,原则不“自动神奇地”绑在一起的关联,但是你可以更新实体的添加/删除方法来做到这一点。
https://gist.github.com/Ocramius/3121916
下面的例子是基于OP的项目/类别架构。 它假定表是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();
有人知道吗?我试了一切我可以删除该项目,它也将从多到多的表中删除,但这次我只是想取消它们的链接。我需要它们存在但不与某个类别相关联.. –