删除关系原则

时间:2011-04-26 10:19:05

标签: doctrine-orm

最简单的是我有一个User和Category类,一个用户可以属于多个类别,定义为

 class Application_Model_User {

    public function __construct() {
        $this->userCategory = new ArrayCollection();
    }
 /**
 * Unidirectional - Users have multiple categories they belong to
 *
 * @ManyToMany(targetEntity="Application_Model_Category")
 * @JoinTable(name="user_category",
 *   joinColumns={@JoinColumn(name="user", referencedColumnName="id")},
 *   inverseJoinColumns={@JoinColumn(name="category", referencedColumnName="id")}
 * )
 */
}
    private $userCategory;

    public function getUserCategories() {
       return $this->userCategory;
  }
 }

为用户添加类别很容易,但我无法理解或从文档中看到我将如何删除特定关系...例如,如果我做了

    $thing = $em->getRepository('Application_Model_User');


$result = $thing->findOneBy(array(
  'id' => (int) 5
));
foreach($result->getUserCategories() as $category) {
    if($category->getName() == 'Another Sub Cat') {
        // Delete this relationship
    }               
}
$em->flush();

我可以删除关系,如果我使用删除删除实体,整个类别会被删除吗?

1 个答案:

答案 0 :(得分:6)

您应该从参考指南中查看Working with Associations。它解释了这一点。

<?php

class Application_Entity_User
{

            // ... snipped for brevity

    public function deleteCategory(Application_Entity_Category $category)
    {
        $this->userCategories->removeElement($category);
    }

}