我试图弄清楚如何在一个表单中使用两个实体。 我有User实体和Profile实体。我创建了一个RegisterType类,其中包含用户实体的字段,之后我在User和Profile之间添加了一对一的映射。现在在我的RegisterType中,我希望有与ProfileEntity相关的字段,如电话,地址。我尝试创建一个ProfileType实例,它是Profile实体的表单生成器类,然后在RegisterType中创建它的实例,如下所示
->add('profile', ProfileType::class, [])
在表单提交后的registerAction方法中,我添加了以下行来添加关系并保存与Profile实体相关的字段的数据。
$user->setProfile($form['profile']->getData()->setUser($user));
我是这样做的,因为如果我没有上述行,它就不会保存用户和个人资料之间的映射。我应该使用什么方法?
答案 0 :(得分:1)
您不需要在registerAction中自行设置配置文件,因为它应该由用户实体中的setter完成。
我几乎可以肯定你的二传手看起来像这样:
Class User
{
setProfile($profile) {
$this->profile = $profile;
}
}
但它一定是这样的:
Class User
{
setProfile($profile) {
$this->profile = $profile;
$profile->setUser($this);
}
}
这与你在setter中所做的相同:)