General error: 1215 Cannot add foreign key constraint - laravel migrations

General error: 1215 Cannot add foreign key constraint - laravel migrations

我正在尝试将几个外键添加到主元 table,如下所示:-

public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('user_id');
            $table->string('author');
            $table->string('title');
            $table->longText('content');
            $table->timestamps();
            $table->engine = 'InnoDB';
        });
    }
public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
            $table->engine = 'InnoDB';
        });
    }
public function up()
    {
        Schema::create('post_tag', function (Blueprint $table) {
            $table->primary(['post_id', 'tag_id']);
            $table->bigInteger('post_id');
            $table->bigInteger('tag_id');
            // $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
            // $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
            $table->timestamps();
            $table->engine = 'InnoDB';
        });

        Schema::table('post_tag', function($table) {
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
            $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
        }); 
        
    }

我 运行 迁移并收到如下错误:-

In Connection.php line 692:

  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
  : alter table `post_tag` add constraint `post_tag_post_id_foreign` foreign
  key (`post_id`) references `posts` (`id`) on delete cascade)


In Connection.php line 485:

  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

环顾网络,我相信它在 primary/foreign 关键数据类型之间存在完整性冲突。例如,具有整数数据类型的外键不能引用类型为 bigInt 的主键。但是,在我的迁移中,我确保类型相同。唉,不管怎样,我仍然得到错误并且我的迁移无法编译?

帮助

bigIncrements 是无符号大整数

$table->bigIncrements('id');

tag_idpost_id 字段类型更改为无符号

$table->unsignedBigInteger('post_id');
$table->unsignedBigInteger('tag_id');

正如您对帖子 table 中的 user_id 所做的那样。

bigIncrements()方法创建一个自增UNSIGNED BIGINT(主键)等价列,所以需要定义unsigned 也适用于外键,因为外键需要与您的主键类型相同:

$table->unsignedBigInteger('post_id');
$table->unsignedBigInteger('tag_id');

// or

$table->bigInteger('post_id')->unsigned();
$table->bigInteger('tag_id')->unsigned();