Php 通过Laravel 5.4中的雄辩,立即插入父母和子女
我试图通过Php 通过Laravel 5.4中的雄辩,立即插入父母和子女,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,我试图通过Eloquent插入两个相关对象,在其中一个表上出现完整性约束冲突错误。以下是我正在尝试的: 关系的表示: class DataParticipant extends Model { public function data_config() { return $this->hasOne('App\Models\DataConfig'); } } class DataConfig extends Model { public fu
Eloquent
插入两个相关对象,在其中一个表上出现完整性约束冲突错误。以下是我正在尝试的:
关系的表示:
class DataParticipant extends Model
{
public function data_config()
{
return $this->hasOne('App\Models\DataConfig');
}
}
class DataConfig extends Model
{
public function data_participant()
{
return $this->belongsTo('App\Models\DataParticipant');
}
}
然后,我尝试以下方法:
$dataParticipant = new DataParticipant();
$dataParticipant->ip = // ip
$dataParticipant->code = // code
$dataParticipant->study_name = // study
// Prepare the config child.
$dataConfig = new DataConfig();
$dataConfig->config = // config via json_encode
// Store the child associated to the parent.
$dataParticipant->data_config()->save($dataConfig);
错误出现在data\u participant\u id
列上,该列属于DataConfig
模型。我的猜测是没有id
可以将两者链接起来。我想问你:
- 我如何做到这一点,而不必先保存
DataParticipant
,然后从数据库中检索它,然后将DataConfig
存储在生成的id
上
首先保存第一个模型
$dataParticipant->save ();
然后保存第二个模型
$dataParticipant->data_config()->save($dataConfig);
这根本不会从数据库中检索数据,$dataParticipant
id将自动设置为最后一个插入id是否尝试保存$dataParticipant
?在创建$dataConfig之前,请$dataParticipant->save()
,如果问题仍然存在,请尝试获取新的$dataParticipant,然后在最后一行中使用它。