首页 > 解决方案 > laravel 迁移 SQLSTATE[HY000]:一般错误:1215 无法添加外键约束

问题描述

当我尝试在 laravel 中运行迁移命令时出现此错误

 Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `posts` add constraint `posts_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

在将此问题标记为重复或否决之前,请完整阅读该问题。

我在这个网站上找到的解决方案是:

  1. 标记为unsigned 我有
  2. 在 2 步中制作整数我有
  3. 架构顺序问题我提供屏幕截图以查看情况并非如此

一

我不确定为什么会出现该错误,这是我的代码:

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug')->unique();
            $table->longText('body');
            $table->string('photo');
            $table->text('meta_description')->nullable();
            $table->text('meta_tags')->nullable();
            $table->integer('user_id')->unsigned();
            $table->string('publish')->default('0');
            $table->string('comment')->default('0');
            $table->timestamps();
});
Schema::table('posts', function (Blueprint $table) {
  $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

任何想法?

更新

用户架构

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

标签: phplaravelschema

解决方案


users表中的主键是BigIncrements创建一个无符号大整数列,但posts表中的外键是整数,所以它们不是同一类型。

将外键更改为bigInteger将修复它。

所以这:

$table->bigInteger('user_id')->unsigned();

代替:

$table->integer('user_id')->unsigned();

推荐阅读