答: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
POPMUISE
相关分类