我在Symfony2和doctrine中有一个小项目,我正在尝试更新2个相关实体:
会员&汽车
$carMembers = $car->getMembers();
echo count($carMembers); // --> show 2
echo get_class(carMembers[0]); // --> show MyCars\WSBundle\Entity\Member
$car->removeMember($member);
$em->persist($car);
$em->flush();
$carMembers= $car->getMembers();
echo count($carMembers); // --> show 1
echo get_class(carMembers[0]); // --> show MyCars\WSBundle\CarsController !!!
有我的实体:
汽车
/**
* @ORM\ManyToMany(targetEntity="Member", mappedBy="cars")
*/
private $members;
/**
* Remove Member
*
* @param MyCars\WSBundle\Entity\Member $member
*/
public function removeMember(\MyCars\WSBundle\Entity\Member $member)
{
$this->members->removeElement($member);
$member->removeCar($this);
}
会员
/**
* @ORM\ManyToMany(targetEntity="Car", cascade={"persist"})
* @ORM\JoinTable(name="cars_membres",
* joinColumns={@ORM\JoinColumn(name="member_id", referencedColumnName="member_id")},
* inverseJoinColumns={@ORM\JoinColumn(name="car_id", referencedColumnName="car_id")}
* )
*/
private $cars;
答案 0 :(得分:10)
我认为您正在寻找的是orphanRemoval
关系选项。
@ORM\ManyToMany(targetEntity="Car", cascade={"persist"}, orphanRemoval=true)
因此,当您从集合中删除项目并刷新实体管理器时,它将从数据库中删除关系记录...
答案 1 :(得分:1)
如果要使用函数添加,包含或 removeElement
<?php
// ...
use Doctrine\Common\Collections\ArrayCollection;
class Car
{
/**
* @MongoDB\Id
*/
protected $members;
/**
* General constructor
*/
public function __construct()
{
$this->members = new ArrayCollection();
}
/**
* @param Member $member
* @return $this
*/
public function addMember(Member $member)
{
if (!$this->hasMember($member)) {
$this->members->add($member);
}
return $this;
}
/**
* @param Member $member
* @return $this
*/
public function removeMember(Member $member)
{
if ($this->hasMember($member)) {
$this->members->removeElement($member);
}
return $this;
}
/**
* @return mixed
*/
public function getMembers()
{
return $this->tags;
}
/**
* @param Member $member
* @return mixed
*/
public function hasTag(Member $member)
{
return $this->members->contains($member);
}
}
答案 2 :(得分:0)
你使用哪个系列?你使用\ Doctrine \ ArrayCollecion吗? 您确定要删除相同的成员对象实例吗? removeElement()方法只有在它是同一个实例时才从集合中删除它。
这是方法(注意array_search方法中的最后一个参数(true):
public function removeElement($element)
{
$key = array_search($element, $this->_elements, true);
if ($key !== false) {
unset($this->_elements[$key]);
return true;
}
return false;
}