Php 在laravel 5中插入相关模型
我使用一个注册表,它允许填写来自两个不同相关模型的数据Php 在laravel 5中插入相关模型,php,orm,model,insert,laravel-5,Php,Orm,Model,Insert,Laravel 5,我使用一个注册表,它允许填写来自两个不同相关模型的数据User和UserProfile,接下来需要将这些数据插入数据库,所有数据都属于一个新条目,换句话说,我在数据库中有一个新的User和一个新的UserProfile 在插入新的用户后,我不知道如何使用相关模型插入用户配置文件 以下是用户型号: class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Auth
User
和UserProfile
,接下来需要将这些数据插入数据库,所有数据都属于一个新条目,换句话说,我在数据库中有一个新的User
和一个新的UserProfile
在插入新的用户
后,我不知道如何使用相关模型插入用户配置文件
以下是用户
型号:
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $fillable = ['first_name', 'last_name','email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function getFullNameAttribute(){
return $this->first_name . ' ' . $this->last_name;
}
public function profile() {
return $this->hasOne('App\UserProfile');
}
}
这里是UserProfile
模型:
class UserProfile extends Model {
protected $fillable = ['bio', 'twitter', 'website', 'birthdate'];
public function getAgeAttribute(){
return \Carbon\Carbon::parse($this->birthdate)->age;
}
}
以下是我试图做的,但我无法做到:
public function postNew(){
$params = Request::all();
$user = new User();
$user->fill($params);
$user->save();
$user->profile->save(new UserProfile($params)); //line 47
}
当我试图运行postNew()
方法时,laravel告诉我以下错误:
FatalErrorException in UserController.php line 47:
Call to a member function save() on null
使用$user->profile()->保存(新的UserProfile($params)) 可能重复的