[英]Cannot add foreign key constraint in Laravel Migration
I've found dozens of similar issues posted, but none of the solutions have seemed to work in my case.我发现发布了几十个类似的问题,但在我的情况下似乎没有一个解决方案有效。 When I run "php artisan migrate:fresh", it's throwing the error...当我运行“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) Illuminate\Database\QueryException:SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter tableslicer_profiles
添加约束slicer_profiles_user_id_foreign
外键(user_id
)在删除级联时引用users
(id
)
I've split the code in to two steps, assigning the foreign key afterwards我将代码分为两步,然后分配外键
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'); });
I check the auth users table and it seems to use an UNSIGNED BIGINT, so I try setting ->unsigned() on the reference as well, but no change.我检查了 auth users 表,它似乎使用了 UNSIGNED BIGINT,所以我也尝试在引用上设置 ->unsigned(),但没有改变。 Any help solving this would be greatly appreciated!任何解决此问题的帮助将不胜感激!
If the users.id
field is a BIGINT then your need to make the users_id
column on slicer_profiles
a BIGINT so that the 2 fields have exact matching types.如果users.id
字段是 BIGINT,那么您需要将 slicer_profiles 上的users_id
列slicer_profiles
为 BIGINT,以便 2 个字段具有完全匹配的类型。
Schema::create('slicer_profiles', function (Blueprint $table) {
...
$table->bigInteger('user_id')->unsigned()->index();
// or $table->unsignedBigInteger('user_id')->index();
...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.