【发布时间】:2021-03-29 13:42:27
【问题描述】:
我有多个具有多个外键的表,但是当我迁移它时找不到另一个迁移,因为它还没有进行。
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');
});
【问题讨论】:
-
这些迁移将始终返回此错误。你有一个循环引用
post表有一个列vote_id引用vote表和vote表有一个列post_id引用post表 - 所以无论哪个迁移首先运行都会出错。再次考虑您的迁移设计/定义为什么需要这样的循环引用
标签: php mysql laravel migration