如何解决GORM - 如何在数据库中嵌入结构和外键关系
我目前有一个结构模型,我在其中声明了两个表之间的多对多关系:StructA 和 StructB。 StructB 有一个 StructA 的列表,这个关联有自己的属性。
// My current model
type StructA struct {
ID uint `json:"id" gorm:"primaryKey"`
PropA string `json:"propA"`
}
type StructB struct {
ID uint `json:"id" gorm:"primaryKey"`
ListStructA []JoinTable `json:"listStructA"`
}
type JoinTable struct {
StructAID uint `json:"-" gorm:"primaryKey"`
StructBID uint `json:"-" gorm:"primaryKey"`
StructA StructA `json:"structA"`
JoinProp int `json:"joinProp"`
}
而 StructB 的编组产生了这种结果
// Current StructB json
{
"id": 1,"listStructA": [
{
"joinProp": 1,"structA": {
"id": 1,"propA": "some prop"
}
}
]
}
通过这个实现,我的数据库模型是高效的。但是我希望 listStructA 对象中的所有属性都在同一层级,因为对于这个 json 的使用者来说,这部分数据包含 structB是很明显的> 属性,并且键入 structB.listStructA[0].structA.propA
而不是 structB.listStructA[0].propA
会让人反感。所以我的最终目标是在编组 structB 时拥有这种结构。
// Wanted StructB json
{
"id": 1,"listStructA": [
{
"id": 1,"propA": "some prop","joinProp": 1,}
]
}
我还指出,在应用程序逻辑中,输入 structB.listStructA[0].joinProp
是有意义的,但不要将 JoinProp 存储在 StructA 中
一种明显的方法是将 JoinTable 中的 StructA 属性作为嵌入结构
type JoinTable struct {
StructA
StructBID uint `json:"-" gorm:"primaryKey"`
JoinProp int `json:"joinProp"`
}
但这会复制JoinTable的数据库表中StructA的数据,而不是引用它(破坏数据库模型)。我能在官方文档中找到有关嵌入式结构的唯一内容是 this section,但它解释了如何做完全相反的事情(在数据库中而不是在代码中嵌入了结构)。
那么在 GORM 中是否有一些预先构建的东西可以两全其美?或者这是否需要我忽略的实现?
我总是可以在最后的手段中为 JoinTable 实现 MarshalJSON 方法,但如果有更聪明的方法,我宁愿不这样做。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。