gpt4 book ai didi

mysql - 交响乐/主义 : OneToMany insert results in null id

转载 作者:行者123 更新时间:2023-11-29 18:04:26 24 4
gpt4 key购买 nike

我有两个实体,我正在尝试对其应用 OneToMany/ManyToOne 关系(一个游戏有多个 GameContent)。

游戏

/**
* @ORM\OneToMany(targetEntity="GameContent", mappedBy="game")
*/
private $contents;

public function __construct()
{
$this->contents = new ArrayCollection();
}

public function getContents()
{
return $this->contents;
}

游戏内容

/**
* @ORM\ManyToOne(targetEntity="Game", inversedBy="contents")
*/
private $game;

以下代码将两条记录插入到各自的表中:

$game = $form->getData();
$content = new GameContent();
$content->setType('some type');
$game->getContents()->add($content);

$em = $this->getDoctrine()->getManager();
$em->persist($content);
$em->persist($game);
$em->flush();

但是,GameContent 的 game_id 会插入为 null:

INSERT INTO game_content (type, game_id) VALUES (?, ?)
Parameters: { 1: 'some type', 2: null }

我也尝试过:

  • 更改 persist() 的顺序
  • 通过执行 $this- 将 $game->getContents()->add($content) 替换为 $game->addContents($content) >contents[] = $content;
  • 删除 Game 实体上的 persist($content) 并添加 cascade={"persist"}

为什么 game_id 被插入为 null?

<小时/>

我当前的解决方法是:

$em = $this->getDoctrine()->getManager();

$game = $form->getData();
$em->persist($game);

$content = new GameContent();
$content->setType('some type');
$content->setGame($game);
$em->persist($content);

$em->flush();

最佳答案

您有 2 个解决方案:

将子项保留在 Controller 中

没有 cascade={"persist"}

$em = $this->getDoctrine()->getManager();

// Get data
$game = $form->getData();

// Create new GameContent and hydrate
$content = new GameContent();
$content->setType('some type');

// Associate Game <> GameContent
$content->setGame($game);

// Persist GameContent
$em->persist($content);

// Persist Game and commit
$em->persist($game);
$em->flush();

让子级保持级联

在 OneToMany 关系中使用 cascade={"persist"}

添加setGame()函数,强制关联:

$game->addContent($this);

并删除持久性:

$em = $this->getDoctrine()->getManager();

// Get data
$game = $form->getData();

// Create new GameContent and hydrate
$content = new GameContent();
$content->setType('some type');

// Associate Game <> GameContent
$content->setGame($game);

// Persist Game and commit
$em->persist($game);
$em->flush();

我认为该错误也是由于坚持游戏的定位造成的。

关于mysql - 交响乐/主义 : OneToMany insert results in null id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48028968/

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