Laravel 迁移因外键而失败

Laravel migration failing with foreign keys

在我的 Laravel 8.x 项目中,我有这个 table 结构:

播放

+--------+---------------------+------+-----+---------+----------------+
| Field  | Type                | Null | Key | Default | Extra          |
+--------+---------------------+------+-----+---------+----------------+
| id     | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| name   | varchar(255)        | NO   |     |         |                |

风景

+------------+---------------------+------+-----+---------+----------------+
| Field      | Type                | Null | Key | Default | Extra          |
+------------+---------------------+------+-----+---------+----------------+
| id         | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255)        | NO   |     | NULL    |                |

play_scenery

+------------+---------------------+------+-----+---------+-------+
| Field      | Type                | Null | Key | Default | Extra |
+------------+---------------------+------+-----+---------+-------+
| play_id    | bigint(20) unsigned | NO   | MUL | NULL    |       |
| scenery_id | bigint(20) unsigned | NO   |     | NULL    |       |

在我的迁移文件中,我想以这种方式添加外键:

Schema::table('play_scenery', function (Blueprint $table) {
    $table->foreign('play_id')
        ->references('id')->on('plays')
        ->onUpdate('cascade')
        ->onDelete('cascade');

    $table->foreign('scenery_id')
        ->references('id')->on('scenerys')
        ->onUpdate('cascade')
        ->onDelete('cascade');
});

失败并显示此消息:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key
constraint (SQL: alter table `play_scenery` add constraint `play_scenery_scenery_id_foreign` foreign key (`scenery_id`)
references `scenerys` (`id`) on delete cascade on update cascade)

我检查了 this 但对这些答案没有任何帮助。

知道我做错了什么吗?

你打错了。 scenerys 应该是 sceneries 以匹配被引用的 table 名称。

 $table->foreign('scenery_id')
        ->references('id')
        ->on('sceneries')
        ->onUpdate('cascade')
        ->onDelete('cascade');
});