答: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 中運行命令時強制執行外鍵。如果我嘗試將 更新owner_id為id中不存在的owners,我會得到:Error: FOREIGN KEY constraint failed,這是我想要的行為,但是,GORM 仍然能夠執行這些更新而不會收到此錯誤。
uj5u.com熱心網友回復:
您需要PRAGMA foreign_keys在更新前執行 exec 查詢才能打開
if res := db.Exec("PRAGMA foreign_keys = ON", nil); res.Error != nil {
return res.Error
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371073.html
