如何在拉拉维尔中一对一地更新关系?

在我的用户模型中,我有以下代码


public function profile()

{

    return $this->hasOne(UserProfile::class);

}

在轮廓模型中,


public function user()

{

   return $this->belongsTo(User::class);

}

create 方法正在工作,但是当我尝试使用以下代码更新配置文件时,它正在创建一个新的配置文件,并且不会更新配置文件信息。


$profile = new UserProfile();

$profile->dob = '1999-03-20';

$profile->bio = 'A professional programmer.';

$profile->facebook = 'http://facebook.com/test/1';

$profile->github = 'http://github.com/test/1';

$profile->twitter = 'http://twitter.com/test/1';


$user = User::find($userId);

$res = $user->profile()->save($profile);

在一对一关系中更新的正确方法是什么?


哈士奇WWW
浏览 81回答 3
3回答

一只萌萌小番薯

我使用推送方法修复了它。这是代码。$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();

慕工程0101907

您正在使用保存方法来保存新记录。使用更新查询//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';]);}//modelfunction updateByUserId($userId,$updateArray){return $this->where('user_id',$userId)->update($updateArray);}

慕斯709654

你做得很好,但我可以建议一点改进您可以使用以下$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', ....]);}
打开App,查看更多内容
随时随地看视频慕课网APP