我有两个实体,我试图将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)并在游戏实体上具有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个解决方案:

坚持控制中的孩子

没有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();


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

10-08 04:04