** 更新问题 **
奇怪的是,我们有Entity
定义了一个简单的关联:
/**
*
* @var MyParent
* @ORM\ManyToOne(targetEntity="MyParent", inversedBy="parents")
*/
private $myParent;
MyParent
看起来像这样:
/**
* @ORM\OneToMany(targetEntity="Entity", mappedBy="myParent")
*/
private $parents;
public function __construct()
{
$this->parents = new ArrayCollection();
}
public function __clone() {
$this->id = null;
}
现在我们通过例如。
来呼叫实体$entity = $repository->find(1);
并获取一个设置了myParent的实体。
现在我们通过克隆它并将其设置为加载的实体来创建一个新的Parent:
$newParent = clone $someOtherMyParent();
$this->em->persist($newParent);
$entity->setParent($newParent);
$this->em->persist($entity);
$this->em->flush();
但新的父级不会与实体一起保存,没有任何反应,没有错误,它只是无声地失败。
使用
$newEntity = new MyParent(); //instead of clone $someOtherMyParent
按预期工作。
我们一定会在这里更新拥有方。发生了什么事?
答案 0 :(得分:2)
这里的问题是,如果您克隆MyParent
,也必须重置集合,否则Doctrine显然不会识别新目标:
public function __clone() {
$this->id = null;
$this->parents = new ArrayCollection(); // this fixes the issue!
}
如果有人能够在评论中解释为什么会这样,那么很高兴知道。