gpt4 book ai didi

symfony - OneToMany 关系不会与新实体一起持续存在

转载 作者:行者123 更新时间:2023-12-01 15:20:47 25 4
gpt4 key购买 nike

当我尝试使用 symfony 表单持久化实体集合时,我遇到了一些问题。我关注了official documentation但由于这个错误,我无法让它工作:

Entity of type ProductItem has identity through a
foreign entity Product, however this entity has no identity itself. You have to call
EntityManager#persist() on the related entity and make sure that an identifier was
generated before trying to persist ProductItem. In case of Post Insert ID
Generation (such as MySQL Auto-Increment or PostgreSQL SERIAL) this means you
have to call EntityManager#flush() between both persist operations.

我必须将实体与 OneToMany 关系链接起来:

产品

/**
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;

/**
* @ORM\OneToMany(targetEntity="ProductItem", mappedBy="product",cascade={"persist"})
*/
protected $items;

和 ProductItem

/**
* @ORM\Id()
* @ORM\ManyToOne(targetEntity="Product", inversedBy="items")
*/
protected $product;

/**
* @ORM\Id()
* @ORM\ManyToOne(targetEntity="Item")
*/
protected $item;

这是它被添加到表单的方式:

->add('items','collection',array(
'label' => false,
'type' => new ProductItemType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false))

这是 Controller Action :

public function newAction()
{
$product= new Product();

$form = $this->createForm(new ProductType(), $product);
if($request->isMethod("POST"))
{
$form->handleRequest($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
}
}
}

我肯定在 Controller 中做错了,因为正如错误消息所说,我必须在添加 $productItems 之前保留 $product,但我该怎么做?

我只会在尝试持久化新实体时出现此错误,如果该实体之前已被持久化,我可以根据需要成功添加任意项目

最佳答案

我上周遇到了完全相同的问题,这是我在阅读和测试后找到的解决方案。

问题是您的 Product 实体具有级联持久化(这通常是好的)并且它首先尝试持久化 ProductItemProductItem 实体无法持久化,因为它们需要 Product首先保留它的 ID(复合键(产品,项目))。

有两个选项可以解决这个问题:

1st 我没有使用它,但您可以简单地删除一个复合键并使用带有外键的标准 id 到 Product

第二 - 更好 这可能看起来像 hack,但请相信我,这是您现在可以做的最好的事情。它不需要对数据库结构进行任何更改,并且可以毫无问题地处理表单集合。

我的代码中的代码片段,文章部分具有 (article_id, random_hash) 的复合键。临时设置对空数组的一对多引用,持久化它,添加原始数据并再次持久化(和刷新)。

    if ($form->isValid())
{
$manager = $this->getDoctrine()->getManager();

$articleSections = $article->getArticleSections();
$article->setArticleSections(array()); // this won't trigger cascade persist
$manager->persist($article);
$manager->flush();

$article->setArticleSections($articleSections);
$manager->persist($article);
$manager->flush();

关于symfony - OneToMany 关系不会与新实体一起持续存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21096352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com