无法在 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,它似乎使用了 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();
    ...
});