Laravel hasone关系 [英] Laravel hasone relationship
本文介绍了Laravel hasone关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用hasone关系,但得到空错误.下面是我的代码
I am trying to use hasone relation but getting null error. below is my code
用户模型:
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()
Error: Call to a member function save() on null
推荐答案
将User.php更改为
Change User.php to
function profile()
{
return $this->hasOne('App\Profile');
}
您需要返回关系实例.
这篇关于Laravel hasone关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文