![](/img/trans.png)
[英]Laravel 8 - CAN delete but CANNOT UPDATE parent row due to integrity constraints violation: foreign key constraint fails
[英]MYSQL Unable to update parent table - Relational Database Design, foreign key constraints and cascading update / delete
我有一個非常簡單的數據庫設計來管理電視節目:
tv_shows
。 主鍵: show_id
seasons
。 主鍵: season_id
,外鍵: show_id
episodes
。 主鍵: episode_id
,外鍵: season_id
表創建SQL:
$sql = "DROP TABLE IF EXISTS ".$table_shows.";
CREATE TABLE $table_shows (
show_id int(11) NOT NULL,
name varchar(120) DEFAULT NULL,
PRIMARY KEY (show_id),
UNIQUE KEY show_id_UNIQUE (show_id)
) $charset_collate;
DROP TABLE IF EXISTS ".$table_seasons.";
CREATE TABLE $table_seasons (
season_id int(10) NOT NULL,
show_id int(11) DEFAULT NULL,
name varchar(120) DEFAULT NULL,
PRIMARY KEY (season_id),
KEY seasons_ibfk_1 (show_id),
CONSTRAINT seasons_ibfk_1 FOREIGN KEY (show_id) REFERENCES $table_shows (show_id) ON DELETE CASCADE ON UPDATE CASCADE
) $charset_collate;
DROP TABLE IF EXISTS ".$table_episodes.";
CREATE TABLE $table_episodes (
episode_id int(10) NOT NULL,
season_id int(10) DEFAULT NULL,
name varchar(120) DEFAULT NULL,
PRIMARY KEY (episode_id),
KEY season_id (season_id),
CONSTRAINT episodes_ibfk_1 FOREIGN KEY (season_id) REFERENCES $table_seasons (season_id)
) $charset_collate;";
我想發生的事情是,如果從tv_shows
表中刪除了某個節目,則刪除級聯,因此seasons
和episodes
也從其各自的表中刪除。
我可以插入這些表中。 但是,如果我嘗試從tv_shows表中刪除一行,則會收到SQL錯誤:
ERROR 1451: 1451: Cannot delete or update a parent row: a foreign key constraint fails
那么我的FK約束哪里出錯了?
您還需要在片段中添加ON DELETE CASCADE
。 這樣可以確保它們彼此跟隨進入垃圾箱。
CONSTRAINT episodes_ibfk_1
FOREIGN KEY (season_id)
REFERENCES $table_seasons (season_id)
ON DELETE CASCADE
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.