3 回答

TA貢獻1795條經驗 獲得超7個贊
我使用推送方法修復了它。這是代碼。
$user = User::find($userId);
$user->name = "Alen";
$user->profile->dob = '1999-03-20';
$user->profile->bio = 'A professional programmer.';
$user->profile->facebook = 'http://facebook.com/test/1';
$user->profile->github = 'http://github.com/test/1';
$user->profile->twitter = 'http://twitter.com/test/1';
$user->push();

TA貢獻1887條經驗 獲得超5個贊
您正在使用保存方法來保存新記錄。使用更新查詢
//controller
$userObj=new User();
if(!empty($userId) && $userId!=null){
$userObj->updateByUserId($userId,[
'dob' = '1999-03-20';
'bio' = 'A professional programmer.';
'facebook' = 'http://facebook.com/test/1';
'github' = 'http://github.com/test/1';
'twitter' = 'http://twitter.com/test/1';
]);
}
//model
function updateByUserId($userId,$updateArray){
return $this->where('user_id',$userId)->update($updateArray);
}

TA貢獻1840條經驗 獲得超5個贊
你做得很好,但我可以建議一點改進
您可以使用以下
$user = User::with('profile')->findOrFail($userId);
if ($user->profile === null)
{
$profile = new UserProfile(['attr' => 'value', ....]);
$user->profile()->save($profile);
}
else
{
$user->profile()->update(['attr' => 'value', ....]);
}
- 3 回答
- 0 關注
- 105 瀏覽
添加回答
舉報