我有一个实体,我想更新其ManyToOne关系。我有FicheSynthese ManyToOne Demandeur关系。当我想编辑FicheSynthese对象时,我发送FicheSynthese和Demandeur表格,其中填充了数据库中的信息。
用户可以决定将Demandeur信息更改为全新的信息。我用AJAX调用处理这种情况,如果不存在Demandeur,则将Demandeur表单的ID字段设置为-1。在这种情况下,我想创建一个Demandeur对象(并在数据库中)并更新FicheSynthese <-> Demandeur关系。
小注释Demandeur是一个抽象类,在4个不同的类中都有继承。在版本上,用户可以更改Demandeur的类型,也可以更改相同类型但仍然是新类型的Demandeur。
我读过几次书,说在更新时我必须更新拥有该关系的实体。如果我正确理解的话,这里是FicheSynthese。
我的实体有一些代码:
Demandeur.php
/**
*@var Collection|FicheSynthese[]
*
*@ORM\OneToMany(targetEntity="FicheSynthese", mappedBy="demandeur", fetch="EXTRA_LAZY")
*
*/
private $ficheSynthese;
public function __construct()
{
$this->ficheSynthese = new ArrayCollection();
}
/**
* @return Collection|FicheSynthese[]
*/
public function getFicheSynthese(): Collection
{
return $this->ficheSynthese;
}
public function addFicheSynthese(FicheSynthese $ficheSynthese): self
{
if (!$this->ficheSynthese->contains($ficheSynthese)) {
$this->ficheSynthese[] = $ficheSynthese;
$ficheSynthese->setDemandeur($this);
}
return $this;
}
public function removeFicheSynthese(FicheSynthese $ficheSynthese): self
{
if ($this->ficheSynthese->contains($ficheSynthese)) {
$this->ficheSynthese->removeElement($ficheSynthese);
// set the owning side to null (unless already changed)
if ($ficheSynthese->getDemandeur() === $this) {
$ficheSynthese->setDemandeur(null);
}
}
return $this;
}
FicheSynthese.php
/**
* @var \Demandeur
*
* @ORM\ManyToOne(targetEntity="Demandeur",
* inversedBy="ficheSynthese", cascade={"persist"})
* @ORM\JoinColumn(name="idDemandeur", referencedColumnName="id")
*/
private $demandeur;
public function getDemandeur(): ?Demandeur
{
return $this->demandeur;
}
public function setDemandeur(?Demandeur $demandeur): self
{
$this->demandeur = $demandeur;
return $this;
}
现在我的控制器(有点混乱):
$em = $this->getDoctrine()->getManager('fichesynthese');
//My Demandeur form
$formsDem[$typeDem]->handleRequest($request);
//I get my Demandeur entity filled
$dem = $formsDem[$typeDem]->getData();
//I get the ID
$id = $dem->getId();
//If ID is -1 that means that my Demandeur doesn't exist
if ($id == -1) {
//I detach the old Demandeur entity, I don't want to remove it
$em->detach($dem);
//I create a new Demandeur entity (which should be the same as $dem)
$newDem = $formsDem[$typeDem]->getData();
//I attach the $newDem to my FicheSynthese that I'm currently editing
$fs->setDemandeur($newDem);
$em->flush();
}
我从Symfony开始,所以我对Doctrine和Entities等的理解是,我不必坚持$ fs,因为它是一种编辑形式。如果我抛弃$ fs,则考虑了Demandeur的更改。问题出在数据库中,它创建了新的Demandeur,但没有更改FicheSynthese表中的外键。另外,它不会更新Demandeur实体中的关系。
我的猜测是,使用-1 ID,它无法更新关系,但是我不明白它如何在FicheSynthese和Demandeur的完全创建中起作用。
更多信息,在我的控制器中,我有一个FicheSynthese表单和一个供需模型使用的数组表单。对于继承,我找不到如何将其嵌入到FicheSynthese形式中。
我在学说和更新中不了解什么?谢谢。
编辑:添加获取器/设置器。