我在为Belongs to
关系创建外键约束时遇到问题。
包含外键的结构:
type Summary struct {
Id string `gorm:"primaryKey"`
OwnerId *string `gorm:"foreignKey:OwnerId references:Id;not null"`
Title string
}
摘要所属的结构:
type Owner struct {
Id string `gorm:"primaryKey"`
Name string
}
它在SQL中创建表没有问题,但SQL模式在owner_id
列的汇总表中不包含外键约束,因此当所有者不存在时可以插入Summary。
3条答案
按热度按时间xdnvmnnf1#
在我看来,最终成功但不是完美的解决方案是在
Summary
中引用Owner
结构体,如下所示:我想知道这是不是唯一的办法
cgfeq70w2#
你用的是什么版本的gorm?如果您使用的是库的v1,请尝试切换到v2。我在使用库的v1时遇到了类似的问题。
v1依赖下载
v2依赖下载
oewdyzsn3#
在我们的例子中,我们需要在列名/字段名方面具有完全的灵活性,因为我们正在迁移一个最初由SQLAlchemy创建的现有数据库。不使用Gorm期望的名称会导致不生成外键。
使用Gorm 2.0,由于某种原因仍然有v1标签(
gorm.io/gorm v1.25.1
),技巧是正确使用foreignkey
(必须指向本地字段)和references
(大多数指向外部表中的远程字段)注解完全任意的名称:这将产生正确的外键关系: