保持具有 OneToMany 关系的父实体使子实体 entity_id 字段在 MySQL 中为 NULL

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 表单(根据 the documentation)的 StructureType 表单保存新的 Structure 时,两个 StructureReferent 实体保存在数据库中,除了 referent table 中的 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"}之前,我在提交表单时出现以下错误:

如有任何帮助,我们将不胜感激。


编辑#1

根据要求,这里是关系的反面:

/**
 * @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;
}

您缺少 JoinColumn() 注释

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Structure", inversedBy="referent")
 * @ORM\JoinColumn()
 */
private $structure;

为了让 Symfony 表单正确处理 adder/remover 的集合,您需要在您的 StructureType class 中添加选项 'by_reference' => false。是这样吗?

$builder->add('referents', CollectionType::class, array('by_reference' => false))

https://symfony.com/doc/current/form/form_collections.html