Delete Relationship Doctrine
In its simplest for I have a User and Category class, a User can belong to multiple Categories, defined as such
class Application_Model_User {
public function __construct() {
$this->userCategory = new ArrayCollection();
}
/**
* Unidirectional - Users have multiple categories they belong开发者_如何学JAVA 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;
}
}
Adding a Category for a user is easy, but I cannot understand or see from the doc's how I would delete a particular relationship... For instance if I did
$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();
I would be able to delete the relationship, if I delete the entity using remove, the whole category is removed?
You should check out Working with Associations from the reference guide. It explains this.
<?php
class Application_Entity_User
{
// ... snipped for brevity
public function deleteCategory(Application_Entity_Category $category)
{
$this->userCategories->removeElement($category);
}
}
精彩评论