![](/img/trans.png)
[英]Entity's id of parent is not saved in a OneToMany relationship in SonataAdmin
[英]Persisting parent entity with OneToMany relationship make child entity entity_id field NULL in MySQL
所以我有这个Symfony 4应用程序,它位于我的主要实体Structure
。 它具有与以下关联存储的属性$referent
(基本上是联系信息):
/**
* @ORM\OneToMany(targetEntity="App\Entity\Referent", mappedBy="structure", cascade={"persist"})
*/
private $referent;
及其获取器和设置器:
/**
* @return Collection|Referent[]
*/
public function getReferent(): Collection
{
return $this->referent;
}
public function addReferent(Referent $referent): self
{
if (!$this->referent->contains($referent)) {
$this->referent[] = $referent;
$referent->setStructure($this);
}
return $this;
}
public function removeReferent(Referent $referent): self
{
if ($this->referent->contains($referent)) {
$this->referent->removeElement($referent);
// set the owning side to null (unless already changed)
if ($referent->getStructure() === $this) {
$referent->setStructure(null);
}
}
return $this;
}
注意,所有代码都是由$ php bin/console make:entity
自动生成的。
问题是,每当我使用嵌入多个ReferentType
表单的StructureType
表单保存新的Structure
(根据文档 ), Structure
和Referent
实体都保存在数据库中,不同的是,根据以下屏幕快照, referent
表中的structure_id
设置为NULL
。
这是处理表单显示和提交的控制器操作:
/**
* @Route("/add", name="back_add")
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function add(Request $request)
{
$structure = new Structure();
$form = $this->createForm(StructureType::class, $structure, [
'attr' => ['id' => 'add-form'],
]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$structure = $form->getData();
$manager = $this->getDoctrine()->getManager();
$manager->persist($structure);
$manager->flush();
return $this->redirectToRoute('back_update', ['id' => $structure->getId()]);
}
return $this->render('back/add.html.twig', [
'form' => $form->createView(),
'action' => __FUNCTION__,
]);
}
那为什么呢?
另外,请注意,在关系注释上添加, cascade={"persist"}
,我在提交表单时遇到以下错误:
任何帮助将非常感激。
根据要求,这里关系的反面:
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Structure", inversedBy="referent")
*/
private $structure;
使用其获取器和设置器:
public function getStructure(): ?Structure
{
return $this->structure;
}
public function setStructure(?Structure $structure): self
{
$this->structure = $structure;
return $this;
}
为了使Symfony表单可以使用加法器/删除器正确处理集合,您需要在StructureType类中添加选项'by_reference'=> false。 是这样吗?
$builder->add('referents', CollectionType::class, array('by_reference' => false))
您缺少JoinColumn()批注
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Structure", inversedBy="referent")
* @ORM\JoinColumn()
*/
private $structure;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.