【发布时间】:2017-12-29 22:10:49
【问题描述】:
我尝试将 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()的顺序 - 将
$game->getContents()->add($content)替换为$game->addContents($content)通过执行$this->contents[] = $content; - 删除
persist($content)并在 Game 实体上添加cascade={"persist"}。
为什么game_id 被插入为空?
我目前的解决方法是:
$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();
【问题讨论】:
标签: mysql symfony doctrine-orm symfony-2.8