无法在 Laravel 迁移中添加外键约束
Cannot add foreign key constraint in Laravel Migration
我发现有许多类似的问题已发布,但 none 的解决方案似乎适用于我的情况。当我 运行 "php artisan migrate:fresh" 时,它抛出错误...
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error:
1215 Cannot add foreign key constraint (SQL: alter table
slicer_profiles
add constraint slicer_profiles_user_id_foreign
foreign key (user_id
) references users
(id
) on delete cascade)
- 创建的所有 table 都是 InnoDB
- 'users' table 在我的 table
之前创建
我把代码分成两步,然后分配外键
Schema::create('slicer_profiles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->string('title');
$table->text('description');
$table->string('slicer');
$table->string('machine');
$table->softDeletes();
$table->timestamps();
});
Schema::table('slicer_profiles', function($table) {
$table->foreign('user_id')->unsigned()
->references('id')
->on('users')
->onDelete('cascade');
});
我检查了授权用户 table,它似乎使用了 UNSIGNED BIGINT,所以我也尝试在引用上设置 ->unsigned(),但没有改变。任何解决此问题的帮助将不胜感激!
如果 users.id
字段是 BIGINT,那么您需要将 slicer_profiles
上的 users_id
列设为 BIGINT,以便这 2 个字段具有完全匹配的类型。
Schema::create('slicer_profiles', function (Blueprint $table) {
...
$table->bigInteger('user_id')->unsigned()->index();
// or $table->unsignedBigInteger('user_id')->index();
...
});
我发现有许多类似的问题已发布,但 none 的解决方案似乎适用于我的情况。当我 运行 "php artisan migrate:fresh" 时,它抛出错误...
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
slicer_profiles
add constraintslicer_profiles_user_id_foreign
foreign key (user_id
) referencesusers
(id
) on delete cascade)
- 创建的所有 table 都是 InnoDB
- 'users' table 在我的 table 之前创建
我把代码分成两步,然后分配外键
Schema::create('slicer_profiles', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned()->index(); $table->string('title'); $table->text('description'); $table->string('slicer'); $table->string('machine'); $table->softDeletes(); $table->timestamps(); }); Schema::table('slicer_profiles', function($table) { $table->foreign('user_id')->unsigned() ->references('id') ->on('users') ->onDelete('cascade'); });
我检查了授权用户 table,它似乎使用了 UNSIGNED BIGINT,所以我也尝试在引用上设置 ->unsigned(),但没有改变。任何解决此问题的帮助将不胜感激!
如果 users.id
字段是 BIGINT,那么您需要将 slicer_profiles
上的 users_id
列设为 BIGINT,以便这 2 个字段具有完全匹配的类型。
Schema::create('slicer_profiles', function (Blueprint $table) {
...
$table->bigInteger('user_id')->unsigned()->index();
// or $table->unsignedBigInteger('user_id')->index();
...
});