一般错误:1215不能添加外键约束- laravel迁移



我正在尝试添加一对外键到数据透视表,如下所示:-

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

环顾网络,我相信这是主键/外键数据类型之间的完整性冲突。例如,具有整数数据类型的外键不能引用bigInt类型的主键。但是,在我的迁移中,我要确保类型是相同的。唉,无论如何,我仍然得到错误,我的迁移无法编译?

帮助

bigIncrements为大无符号整数

$table->bigIncrements('id');

tag_id,post_id字段类型更改为unsigned

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

就像您在posts表中处理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();

最新更新