在我的Laravel 8.x项目中,我有这样的表结构:
播放
+--------+---------------------+------+-----+---------+----------------+
| 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 | |
播放场景
+------------+---------------------+------+-----+---------+-------+
| 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)
我检查了一下,但对这些答案都没有帮助。
知道我做错了什么吗?
您有一个打字错误。scenerys
应为sceneries
,以匹配所引用的表名。
$table->foreign('scenery_id')
->references('id')
->on('sceneries')
->onUpdate('cascade')
->onDelete('cascade');
});