在保存hasMany
关系之前,Laravel要求您保存父模型是否正常?我可以在保存模型之前使用belongsTo
。
$team = new Team();
$team->tournament()->associate($tournament);
// $team->save(); without this line, it will throw an error
$team->players()->save(new TeamPlayer([
'user_id' => 1
]));
$team->save();
团队模型的关系如下所示:
public function players()
{
return $this->hasMany(TeamPlayer::class);
}
public function tournament()
{
return $this->belongsTo(Tournament::class);
}
抛出的错误是这个
Integrity constraint violation: 1048 Column 'team_id' cannot be null (SQL: insert into `team_players` (`user_id`, `team_id`, `updated_at`, `created_at`) values (1, , 2017-12-18 13:32:29, 2017-12-18 13:32:29))