如何在Laravel中更新 OneToOne 关系
例如,下面的代码将在您第一次保存时保存。但是如果我尝试更新它就会遇到问题
$profile = new Profile();
$profile->dob = '20-03-1999';
$profile->bio = 'A professional programmer.';
$user = User::find(1);
$user->profile()->save($profile);
这是我要更新个人资料的代码:
$user = User::find(1);
$profile = Profiles::where('user_id', $user->id)->get();
$profile->bio = 'i now read.';
$user->profile()->save($profile);
错误消息:
TypeError
Argument 1 passed to
Illuminate\Database\Eloquent\Relations\HasOneOrMany::save()
must be an instance of Illuminate\Database\Eloquent\Model,
instance of Illuminate\Database\Eloquent\Collection given
答案 0 :(得分:1)
您必须执行以下任一操作:
$user = User::find(1);
$profile = Profiles::where('user_id', $user->id)->first();
$profile->dob = '20-03-1999';
$profile->bio = 'A professional programmer.';
$profile->save();
或者这个:
$user = User::find(1);
$user->profile()->update([
'bio' => 'aaa',
'dob' => 'bbb',
]);
答案 1 :(得分:0)
您拥有user_id,因此无需获取用户集合。
尝试这两种方法
第一种方法
$profile = Profiles::where('user_id', 1)->first();
$profile->bio = 'i now read.';
$profile->save();
第二种方式
使用关系。
$user = User::find(1);
$user->profile()->update([
'bio' => 'i now read.',
'dob' => '20-03-1999',
]);
第三次直接更新
Profiles::where('user_id', 1)->update([
'bio' => 'i now read.',
'dob' => '20-03-1999',
]);