首页 > 解决方案 > Laravel 向多个表中插入数据

问题描述

嗨,我需要将注册表单中的数据插入 2 或 3 个表、用户和成员。当您单击注册按钮时,我需要仅将用户 ID 和密码发送到 users.table 并将其余信息发送到 members.table

*编辑我的模型

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 = [
    'name', 'email', 'password', 'admin', 'predmet', 
];

/**
 * 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',
];
}

我的迁移

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->integer('admin');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('users');
}
}

我需要将 id、predmet 和 name 导入成员表的 cote

标签: phphtmlmysqllaravel

解决方案


首先,您的所有字段都像这样创建 nullable()

Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name')->nullable();
        $table->integer('admin')->nullable();
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken()->nullable();
        $table->timestamps();
    });

然后在控制器中

public function store()
{
        $user = new User;
        $user->password = bcrypt($request->password);
        $user->save();
        $member = new Member;
        $member->name = $request->name;
        $member->username = $request->username; 
        $member->email= $request->email; 
        $member->save();
        return back();

}

推荐阅读