Laravel 如何向 2 个表中插入数据?

我的用户模型


<?php


namespace App;


use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;


class User extends Authenticatable

{

    use Notifiable;


    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    protected $fillable = [

        'role_id', 'name', 'email', 'password',

    ];


    /**

     * The attributes that should be hidden for arrays.

     *

     * @var array

     */

    protected $hidden = [

        'password', 'remember_token',

    ];


    /**

     * The attributes that should be cast to native types.

     *

     * @var array

     */

    protected $casts = [

        'email_verified_at' => 'datetime',

    ];

}

医院模型



namespace App;


use Illuminate\Database\Eloquent\Model;


class Hospital extends Model

{

    /**

     * @var String $table;

     */

    protected $table = 'hospitals';


    /**

     * @var Array $fillable;

     */


    protected $fillable = [

        'user_id', 'companyname', 'adress', 'postalcode', 'residence',

        'phonenumber', 'mailadress'

    ];

}


青春有我
浏览 100回答 1
1回答

梦里花落0921

首先你不需要像这样在你的动作中注入User模型storepublic function store(User $user, Request $request)您可以在hospital控制器的store操作中使用类似以下代码的事务public function store(Request $request){&nbsp; &nbsp; $request->validate([&nbsp; &nbsp; &nbsp; &nbsp; 'name' => 'required|max:255',&nbsp; &nbsp; &nbsp; &nbsp; 'email' => 'required|max:255|unique:users',&nbsp; &nbsp; &nbsp; &nbsp; 'password' => 'required|min:8',&nbsp; &nbsp; ]);&nbsp; &nbsp; DB::transaction(function () use($request){&nbsp; &nbsp; &nbsp; &nbsp; // $user = User::create($this->transformForm($request));&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $user = User::create([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'name' => $request->input('name'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'email' => $request->input('email'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'password' => $request->input('password'),&nbsp; &nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; &nbsp; &nbsp; // update or insert here&nbsp; &nbsp; &nbsp; &nbsp; Hospital::Create([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'user_id' => $user->id,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'companyname' => $request->input('companyname'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'adress' => $request->input('adress'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'postalcode' => $request->input('postalcode'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'residence' => $request->input('residence'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 'phonenumber' => $request->input(), //missing in your form&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 'mailadress' => $request->input() // missing in your form&nbsp; &nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; });&nbsp; &nbsp; return //redirecto to a success page or somewhere else}
打开App,查看更多内容
随时随地看视频慕课网APP