Laravel迁移-一般错误:1215无法添加外键约束



我有多个带有多个外键的表,但当我迁移时,它还找不到其他迁移,因为它还没有完成。

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `post` add constraint `post_vote_id_foreign` foreign key (`vote_id`) references `vote` (`id`))

后表

Schema::create('post', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('topic_id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('vote_id');
$table->string('title');
$table->string('summary');
$table->string('image');
$table->timestamps();
$table->foreign('topic_id')->references('id')->on('topic');
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('vote_id')->references('id')->on('vote');
});

投票表查看后的所有投票

Schema::create('vote', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('post_id');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('post_id')->references('id')->on('post');
$table->foreign('user_id')->references('id')->on('users');
});

尽管有循环引用并不好,但很可能表明设计不好。然而,如果你真的想有循环参考

Schema::create('post', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('topic_id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('vote_id');
$table->string('title');
$table->string('summary');
$table->string('image');
$table->timestamps();
$table->foreign('topic_id')->references('id')->on('topic');
$table->foreign('user_id')->references('id')->on('users');
});

在创建投票表后,您可以更改发布表以定义外键

Schema::create('vote', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('post_id');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('post_id')->references('id')->on('post');
$table->foreign('user_id')->references('id')->on('users');
});
Schema::table('post', function(Blueprint $table) {
$table->foreign('vote_id')->references('id')->on('vote');
});

需要注意的是,迁移文件按创建顺序运行。因此,请仔细检查您的表设计,先获得那些独立的表(更改它们的文件名,即时间戳,使它们先出现(,然后再获得依赖的表(具有独立表外键的表(。我希望你能理解?

对于谷歌人。。。在我的情况下,这是因为父表是myIsam类型,而不是innodb

最新更新