【问题标题】:Insert related model in laravel 5在 laravel 5 中插入相关模型
【发布时间】:2015-05-07 06:25:03
【问题描述】:

我使用了一个注册表,允许从UserUserProfile两个不同的相关模型中填写数据,接下来需要将这些数据插入数据库中,所有数据都属于一个新条目,换句话说我在数据库中有一个新的User 和一个新的UserProfile

插入新的User后不知道如何使用相关模型插入UserProfile

这里是User 模型:

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

【问题讨论】:

标签: php orm model insert laravel-5


【解决方案1】:

使用 $user->profile() ->save(new UserProfile($params));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2014-08-29
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2014-07-02
    相关资源
    最近更新 更多