如何在Laravel中以一对一的关系进行更新?

问题描述 投票:0回答:3

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

public function profile()
{
    return $this->hasOne(UserProfile::class);
}

在个人资料模型中,

public function user()
{
   return $this->belongsTo(User::class);
}

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

$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);

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

php laravel-5 eloquent orm relationship
3个回答
0
投票

您做得对,但是我可以提出一点改进

您可以使用以下内容

$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', ....]);
}

0
投票

您正在使用保存方法来保存新记录。使用更新查询

//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);
}

0
投票

我使用推送方法修复了它。这是代码。

$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();
© www.soinside.com 2019 - 2024. All rights reserved.