繁体   English   中英

保持具有OneToMany关系的父实体在MySQL中使子实体entity_id字段为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表单的StructureType表单保存新的Structure (根据文档 ), StructureReferent实体都保存在数据库中,不同的是,根据以下屏幕快照, 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"} ,我在提交表单时遇到以下错误:

在此处输入图片说明

任何帮助将非常感激。


编辑#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;
}

为了使Symfony表单可以使用加法器/删除器正确处理集合,您需要在StructureType类中添加选项'by_reference'=> false。 是这样吗?

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

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

您缺少JoinColumn()批注

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM