在Laravel 5.6中一次插入父级和子级

时间:2018-07-07 15:54:41

标签: laravel laravel-5 insert

我试图同时在usersuser_details表中插入数据。参见下面的代码:

型号:

class User extends Authenticatable
{
    public function user_detail() {
        return $this->hasOne('App\UserDetail', 'user_id');
    }
}

查看:

<div class="form-group{{ $errors->has('username') ? ' has-error' : ''}}">
    {!! Form::label('username', 'Username:* ', ['class' => 'col-md-4 control-label']) !!}
    <div class="col-md-6">
        {!! Form::text('username', null, ['class' => 'form-control', 'required' => 'required']) !!}
        {!! $errors->first('username', '<p class="help-block">:message</p>') !!}
    </div>
</div>
...
<div class="form-group{{ $errors->has('user_detail[about_me]') ? ' has-error' : ''}}">
    {!! Form::label('user_detail[about_me]', 'About Me: ', ['class' => 'col-md-4 control-label']) !!}
    <div class="col-md-6">
        {!! Form::textarea('user_detail[about_me]', null, ['class' => 'form-control', 'required' => 'required']) !!}
        {!! $errors->first('user_detail[about_me]', '<p class="help-block">:message</p>') !!}
    </div>
</div>

控制器:

public function store(Request $request) {
    $data = $request->except('password'); //dd($data);
    $user = User::create($data);
    $user->user_detail->create($data['user_detail']);
}

错误消息:

enter image description here

在上面,我已经发布了我的代码(已删除的休息字段。仅保留用户表username和user_details about_me

在我上面的代码中,数据已成功插入users表中,但在子表中插入时发生了错误。

请查看我的代码,并建议我如何在子表中插入记录。

1 个答案:

答案 0 :(得分:4)

错误的代码是$user->user_detail。它必须是nullUserDetail的实例,因为您现在已经创建了用户$user->user_detail,所以它必须是null。您必须使用$user->user_detail()而不是$user->user_detail。更正的代码是

public function store(Request $request) 
{
    $data = $request->except('password');
    $user = User::create($data);
    if ($user) {
        $user->user_detail()->create($data['user_detail']);
    }
}