一個相當古老的帖子,但希望提供一種方法來確保關聯已從教條的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();
有人知道嗎?我試了一切我可以刪除該項目,它也將從多到多的表中刪除,但這次我只是想取消它們的鏈接。我需要它們存在但不與某個類別相關聯.. –