【问题标题】:How to update in one to one relation in laravel?如何在 laravel 中以一对一的关系更新?
【发布时间】:2020-02-18 05:39:11
【问题描述】:

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

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

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

【问题讨论】:

    标签: php laravel-5 eloquent orm relationship


    【解决方案1】:

    你做得对,但我可以建议一些改进

    你可以使用以下

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

    【讨论】:

    • 感谢您对此的回复。但是,我不想使用数组。就像在 Laravel 文档中一样,如果记录已经退出,save 方法应该更新记录。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2015-03-24
        • 2016-07-22
        • 1970-01-01
        • 2020-03-13
        • 2018-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-31
        相关资源
        最近更新 更多