所以这是我在EventListener上的prePersist
public function prePersist(LifecycleEventArgs $args)
{
//the first entity will have the PMP, so we catch it and continue to skip this if after this
if ($this->pmp == null) {
$this->pmp = $args->getEntity()->getPmp();
}
$taxonomicClass = $args->getEntity();
if($taxonomicClass instanceof TaxonomicClass){
if(is_null($taxonomicClass->getId())){
//here it says that i have created a new entity, need to persist it via cascade={"persist"}
$taxonomicClass->setPmp($this->pmp);
}
}
}
没关系,我在其上添加了注释:
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Pmp", cascade={"persist"})
* @ORM\JoinColumn(name="pmp_id", referencedColumnName="id", nullable=false)
**/
private $pmp;
它保存了我的层次结构中的所有内容,甚至是新的PMP,数据库中已经存在的对象!
我想要的是从我的层次结构中保存的所有内容都需要与我传递的PMP相关,但是当我设置$taxonomicClass->setPmp($this->pmp);
时,我认为我创建了一个新的PMP实例,因为我不是,我只想要这个人与PMP有联系。
我尝试将merge
放在级联选项上,但它只适用于persist
,如何使doctrine不创建新实例,而是使用我传递的实例?
答案 0 :(得分:0)
注意到我的问题,我从记忆中分配了一个属性,我应该将他从数据库中恢复到学说理解。
public function prePersist(LifecycleEventArgs $args)
{
if ($this->pmp == null) {
$this->pmp = $args->getEntity()->getPmp();
}
$taxonomicClass = $args->getEntity();
if($taxonomicClass instanceof TaxonomicClass){
if(is_null($taxonomicClass->getId())){
//this solved the problem
$pmp = $args->getEntityManager()->getRepository("AppBundle:Pmp")->find($this->pmp->getId());
$taxonomicClass->setPmp($pmp);
}
}
}
我现在要记住,当创建一个新实体但不需要保存时,你必须从db中检索它,cascade={"persist"}
甚至没有必要