Laravel 用关系存储记录

Laravel 用关系存储记录,laravel,Laravel,我试图存储一个记录(user),它有一个相关的类(userprofile)。如何在一次运行中存储它们?我试过以下方法 公共函数存储(UserRequest$request,User$model) { $model->create($request->合并)([ 'picture'=>$request->photo?$request->photo->store('profile','public'):null, 'password'=>Hash::make($request->get('passw

我试图存储一个记录(user),它有一个相关的类(userprofile)。如何在一次运行中存储它们?我试过以下方法

公共函数存储(UserRequest$request,User$model)
{
$model->create($request->合并)([
'picture'=>$request->photo?$request->photo->store('profile','public'):null,
'password'=>Hash::make($request->get('password'))
])->全部());
$model->userprofile()->创建([
“userprofile_firstname”=>“firstname”,
“userprofile\u lastname”=>“lastname”,
'userprofile_phone'=>'phone',
'userprofile_created'=>Carbon::now(),
'userprofile_createdbyid'=>Auth::id(),
]);
return redirect()->route('user.index')->with status(_uu('user added'));
}
但这给了我一个约束错误,因为userprofile_userid(用户的ID和外键关系)是空的

关系的配置如下所示:

$user = $model->create($request->merge([
    'picture' => $request->photo ? $request->photo->store('profile', 'public') : null,
    'password' => Hash::make($request->get('password'))
])->all());


$model->userprofile()->create([
    "userprofile_userid" => $user->id,
    "userprofile_firstname" => "firstname",
    "userprofile_lastname" => "lastname",
    "userprofile_phone" => "phone",            
    "userprofile_created" => Carbon::now(),
    "userprofile_createdbyid" => Auth::id(),
]);
公共函数userprofile()
{
返回$this->hasOne(Userprofile::class,'Userprofile_userid');
}
公共功能用户()
{
返回$this->hasOne(用户::类);
}

保存用户后,我是否应该手动查找用户以获取其ID?我假设由于配置了关系,Laravel会自动填充id。

当您创建using create函数时,它将返回用户,以便您以后可以像这样使用它:

$user = $model->create($request->merge([
    'picture' => $request->photo ? $request->photo->store('profile', 'public') : null,
    'password' => Hash::make($request->get('password'))
])->all());


$model->userprofile()->create([
    "userprofile_userid" => $user->id,
    "userprofile_firstname" => "firstname",
    "userprofile_lastname" => "lastname",
    "userprofile_phone" => "phone",            
    "userprofile_created" => Carbon::now(),
    "userprofile_createdbyid" => Auth::id(),
]);
根据官方文件

一旦我们使属性可分配,我们就可以使用create方法在数据库中插入一条新记录。create方法返回保存的模型实例:


由于某些原因,该操作失败,并出现“SQLSTATE[23000]:完整性约束冲突:1048列“userprofile\u userid”不能为空。如果我添加$user->id,我确实得到了正确的id。所以我很困惑为什么SQL语句要插入NULLok,更改$model->userprofile()->create([到$userprofile=$user->userprofile()->create([完成了任务。谢谢!)!!