为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
青春有我 2022-12-30 17:07:47
我的用户模型<?phpnamespace 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'    ];}
查看完整描述

1 回答

?
梦里花落0921

TA贡献1772条经验 获得超6个赞

首先你不需要像这样在你的动作中注入User模型store


public function store(User $user, Request $request)

您可以在hospital控制器的store操作中使用类似以下代码的事务


public function store(Request $request)

{

    $request->validate([

        'name' => 'required|max:255',

        'email' => 'required|max:255|unique:users',

        'password' => 'required|min:8',

    ]);


    DB::transaction(function () use($request){

        // $user = User::create($this->transformForm($request)); 


        $user = User::create([

            'name' => $request->input('name'),

            'email' => $request->input('email'),

            'password' => $request->input('password'),

        ]);


        // update or insert here

        Hospital::Create([

            'user_id' => $user->id,

            'companyname' => $request->input('companyname'),

            'adress' => $request->input('adress'),

            'postalcode' => $request->input('postalcode'),

            'residence' => $request->input('residence'),

            // 'phonenumber' => $request->input(), //missing in your form

            // 'mailadress' => $request->input() // missing in your form

        ]);

    });


    return //redirecto to a success page or somewhere else

}


查看完整回答
反对 回复 2022-12-30
  • 1 回答
  • 0 关注
  • 99 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信