我需要一些帮助才能理解我做错了什么,我试图在这里搜索一个答案,但没有任何效果。
这里是我的问题..
我有两个具有一对一关系的实体:
...
class FarmInfo
{
...
/**
* @var integer
*
* @ORM\Column(name="areaCovered", type="integer", nullable=true)
*/
private $areaCovered;
/**
* @var integer
*
* @ORM\Column(name="totalIrrigatedArea", type="integer", nullable=true)
*/
private $totalIrrigatedArea;
/**
* @var integer
*
* @ORM\Column(name="totalStaff", type="integer", nullable=true)
*/
private $totalStaff;
/**
* @var DairyInfo
* @ORM\OneToOne(targetEntity="DairyInfo", mappedBy="farmInfo", cascade={"persist","remove"})
*/
private $dairyInfo;
...
}
和
...
class DairyInfo
{
...
/**
* @var FarmInfo
*
* @ORM\OneToOne(targetEntity="FarmInfo", inversedBy="dairyInfo", cascade={"persist"})
* @ORM\JoinColumn(name="farmInfoId", referencedColumnName="id")
*
*/
private $farmInfo;
/**
* @var integer
*
* @ORM\Column(name="peakCowMilked", type="integer", nullable=true)
*/
private $peakCowMilked;
/**
* @var integer
*
* @ORM\Column(name="cowsMilkedInWinter", type="smallint", nullable=true)
*/
private $cowsMilkedInWinter;
...
}
这里是formTypes:
class FarmInfoType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('areaCovered');
$builder->add('totalIrrigatedArea');
$builder->add('totalStaff');
$builder->add('dairyInfo', new DairyInfoType());
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'FOO\CoreBundle\Entity\FarmInfo'
));
}
/**
* @return string
*/
public function getName()
{
return 'foo_corebundle_farminfo';
}
}
class DairyInfoType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('peakCowMilked');
$builder->add('cowsMilkedInWinter');
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'FOO\CoreBundle\Entity\DairyInfo'
));
}
/**
* @return string
*/
public function getName()
{
return 'foo_corebundle_dairyinfo';
}
}
使用与我想要的相同形式为FarmInfo和DairyInfo创建表单,但是当我坚持使用时,FarmInfo仍然存在,DairyInfo会保留所有字段,但farmInfoId始终为null:
+---------------+--------------------+------------+
| peakCowMilked | cowsMilkedInWinter | farmInfoId |
+---------------+--------------------+------------+
| 11 | 11 | NULL |
+---------------+--------------------+------------+
我需要做什么才能让symfony自动获取此ID?
谢谢大家的提前。
答案 0 :(得分:8)
你没有展示你的方法,但我相当肯定你有:
class FarmInfo
{
setDairyInfo($dairyInfo)
{
$this->dairyInfo = $dairyInfo;
}
}
问题是没有任何东西在您的dairyInfo类中设置farmInfo。因此,将setDairyInfo修改为:
setDairyInfo($dairyInfo)
{
$this->dairyInfo = $dairyInfo;
$dairyInfo->setFarmInfo($this);
}
你应该好好去。