答:db.Exec("PRAGMA foreign_keys = ON")用于強制執行外鍵約束檢查。謝謝@outdead當我使用 GORM 更新我的 SQLite 數據庫時,不會強制執行外鍵約束。我有這兩個模型:type Cat struct { ID int Name string Breed string OwnerID int Owner Owner }type Owner struct { ID int Name string Phone string}它正確地創建了一個外鍵約束,其中owner_id引用id. owners這可以通過.schema cats在 SQLite shell 中運行:CREATE TABLE `cats` (`id` integer,`name` text,`breed` text,`owner_id` integer,PRIMARY KEY (`id`),CONSTRAINT `fk_cats_owner` FOREIGN KEY (`owner_id`) REFERENCES `owners`(`id`));我試過PRAGMA foreign_keys = ON;在 SQLite shell 中運行命令時強制執行外鍵。如果我嘗試將 an 更新為中不存在的owner_idan ,我會得到:,這是我想要的行為,但是,GORM 仍然能夠執行這些更新而不會收到此錯誤。idownersError: FOREIGN KEY constraint failed
在 GORM SQLite 中強制執行外鍵約束
慕尼黑5688855
2022-10-17 16:05:22