【问题标题】:Laravel hasone relationshipLaravel hasone 关系
【发布时间】:2020-10-06 21:16:04
【问题描述】:

我正在尝试使用 hasone 关系,但出现 null 错误。下面是我的代码

用户模型:

  function profile()
{
    $this->hasOne('App\Profile');
}

个人资料模型:

   function User()
{
    return $this->belongsTo('App\User');
}

注册控制器

 protected function create(array $data)
{
    $user =  User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);

    if($user) {

        $profile = new Profile();
        $profile->name = 'Fake Name';
        $profile->father = 'Fake Father';
        $user->profile()->save($profile);
    }

    return $user;

}

错误:在 null 上调用成员函数 save()

【问题讨论】:

    标签: laravel laravel-5 eloquent relationship one-to-one


    【解决方案1】:

    将 User.php 更改为

      function profile()
      {
        return $this->hasOne('App\Profile');
      }
    

    您需要返回关系实例。

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 2017-04-21
      • 2016-03-17
      • 1970-01-01
      • 2020-04-09
      • 2018-05-29
      • 1970-01-01
      • 2018-09-12
      • 2020-03-04
      相关资源
      最近更新 更多