无法在 Laravel 中添加外键
Cant add foreign key in Laravel
当我尝试迁移时出现错误 "Foreign key constraint is incorrectly formed",但我不明白为什么
第一table
Schema::create('uciteles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('admin');
$table->string('predmet');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->timestamps();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
第 2 table
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->timestamps();
});
列的类型必须与外键引用中的相同,您需要自己创建列。
以下是对您问题的解释:Creating Foreign Key in Laravel Migrations
我认为您首先要创建 uciteles table,然后是用户 table。
所以在这里更改 format.first 创建用户 table & 然后 uciteles table.
像这样在迁移中更改创建时间 table 2019_09_27_000000_create_users_table.php 更改日期和月份然后用户 table 首先创建 uciteles table 或禁用外键检查并启用它
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
Schema::create('uciteles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('admin');
$table->string('predmet');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->timestamps();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
当我尝试迁移时出现错误 "Foreign key constraint is incorrectly formed",但我不明白为什么
第一table
Schema::create('uciteles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('admin');
$table->string('predmet');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->timestamps();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
第 2 table
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->timestamps();
});
列的类型必须与外键引用中的相同,您需要自己创建列。
以下是对您问题的解释:Creating Foreign Key in Laravel Migrations
我认为您首先要创建 uciteles table,然后是用户 table。 所以在这里更改 format.first 创建用户 table & 然后 uciteles table.
像这样在迁移中更改创建时间 table 2019_09_27_000000_create_users_table.php 更改日期和月份然后用户 table 首先创建 uciteles table 或禁用外键检查并启用它
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
Schema::create('uciteles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('admin');
$table->string('predmet');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->timestamps();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
DB::statement('SET FOREIGN_KEY_CHECKS=1;');