你好,我的多嵌入表单(一对多)有问题。一个游戏有很多奖品,一个奖品有很多选择。当我试图保存此表单时,会收到错误消息
SQLSTATE[23000]:完整性约束冲突:1048列"fk_prize"不能为空
我已经在我的实体中设置了级联,并在我的表单中设置了类型by_redifference false,但没有起作用。所有其他指定的外键都能很好地工作。
更新:在控制器中,当我完成此表单时,保存成功。但我想用教义来做这件事。这是教条中的错误还是我的代码中的错误?谢谢你抽出时间!
//Hacked code in controller to save the form
$prizes = $data->getPrizes();
foreach ($prizes as $prize) {
$prizeOptions = $prize->getPrizesOptions();
foreach ($prizeOptions as $prizeOption) {
$prizeOption->setPrize($prize);
}
}
$em->persist($data);
$em->flush();
<?php
class Game
{
/**
* @ORMOneToMany(targetEntity="Prize", mappedBy="game", cascade={"persist"})
*/
protected $prizes;
public function __construct()
{
$this->gameUsers = new ArrayCollection();
$this->prizes = new ArrayCollection();
}
}
?>
<?php
class GameType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('alias', 'text' , [
'label'=>'Name'
])
->add('prizes' ,'collection', array(
'type' => new PrizeType($this->intention),
'allow_add' => true,
'allow_delete' => false,
'prototype' => true,
'by_reference' => false,
'label' => false,
))
->add('save', 'submit', [
'attr' => [
'class' => 'btn btn-primary'
]
]);
}
}
<?php
class Prize
{
/**
* The Game
* @ORMManyToOne(targetEntity="Game")
* @ORMJoinColumn(name="game_id", referencedColumnName="id")
*/
protected $game;
/**
* @ORMOneToMany(targetEntity="PrizeOptions", mappedBy="prize", cascade={"persist"})
*/
protected $prizes_options;
/**
* Constructor
*/
public function __construct()
{
$this->prizes_options = new DoctrineCommonCollectionsArrayCollection();
}
}
class PrizeType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('prizes_options' ,'collection', array(
'type' => new PrizeOptionsType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'label' => false,
))
;
}
}
<?php
class PrizeOptionsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text' , [
'label'=>'Value'
])
;
}
}
条令只能在"拥有"一方处理实体中的更改。也就是说,您只能在定义了联接列/联接表的实体中修改关系。http://doctrine-orm.readthedocs.org/en/latest/reference/unitofwork-associations.html