存储在数据库中的最佳方式laravel关系hasmany

时间:2018-01-14 08:03:49

标签: laravel laravel-5

我有两个模型,User和Docente。这些是你的关系

user.php的

public function docente()
{
    return $this->hasOne(Docente::class);
}

Docente.php

public function usuario()
{
   return $this->hasOne(User::class,'id','user_id');
}

要插入新记录,请首先输入users表,然后将该ID发送到Docente模型(表docentes)以进行插入。

public function store(DocenteRequest $request)
{

    $newUser = (new User)->fill($request->only('nivel_id','username','password'));
    $newUser->nivel_id = 2; // fixed
    $newUser->save();

    $newDocente = (new Docente)
                ->fill($request->only('dni','especialidad','sexo','apellido_paterno','apellido_materno','nombre','telefono','direccion','comentario'));
    $newDocente->user_id = $newUser->id;
    $newDocente->save();

    return redirect()->route('docente.index');
}

它有效,但我想知道是否有更优化,可取和优雅的方式来做到这一点。

修改

DocenteRequest

    return [
                'dni' => 'required|digits:8|numeric|unique:docentes,dni',
                'especialidad' => 'required|min:3|max:60',
                'sexo' => 'required|not_in:0',
                'apellido_paterno' => 'required|min:2|max:80',
                'apellido_materno' => 'required|min:2|max:80',
                'nombre' => 'required|min:2|max:80',
                'telefono' => 'required|min:6|max:11',
                'direccion' => 'required|string',
                'username'=>'required|max:100|unique:users',
                'password' => 'required|min:7|max:200',

            ];

2 个答案:

答案 0 :(得分:1)

编辑关系,它应该是belongsTo

public function docente()
{
    return $this->belongsTo('App\User');
}

然后在控制器中为现有docente

添加新的user
$user->docente()->save($newDocente);

答案 1 :(得分:1)

由于您已经使用了质量赋值,请使用create()方法:

public function store(DocenteRequest $request)
{
    $user = User::create($request->except('nivel_id') + ['nivel_id' => 2]);
    $user->docente()->create($request->all());
    return redirect()->route('docente.index');
}

由于质量分配,您不需要使用only(),您只需传递将要过滤的所有数据。

此外,usuario关系应为belongsTo()

public function usuario()
{
   return $this->belongsTo(User::class);
}