Как обновить отношение один к одному в laravel? - PullRequest
0 голосов
/ 18 февраля 2020

В моей пользовательской модели у меня есть следующий код

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

Какой правильный способ обновления в отношениях «один к одному»?

Ответы [ 3 ]

0 голосов
/ 18 февраля 2020

вы используете метод сохранения, чтобы сохранить новую запись. используйте запрос на обновление

//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 голосов
/ 19 февраля 2020

Я исправил это, используя метод pu sh. Вот код.

$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();
0 голосов
/ 18 февраля 2020

Вы делаете правильно, однако я мог бы предложить небольшое улучшение

Вы можете использовать следующее

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