Laravel hasone关系

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

我正在尝试使用hasone关系,但得到空错误。下面是我的代码

用户模型:

  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;

}

错误:对成员函数save()的调用为null

laravel laravel-5 eloquent relationship one-to-one
1个回答
0
投票

将User.php更改为

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

您需要返回关系实例。

© www.soinside.com 2019 - 2024. All rights reserved.