【问题标题】:Gorm Scan Nested StructsGorm 扫描嵌套结构
【发布时间】:2020-10-09 09:17:47
【问题描述】:

我正在尝试使用 gorm 查询 golang 中的视图并将结果保存在包含 NodeType 的结构 EdgeType 中。 (基本上是在尝试实现graphql-relay connection specification)。

视图包含 4 个字段:

cursor   bigint
id       bigint
text     text
user_id  bigint
type NodeType struct {
    ID     int64
    Text   string
    UserID int64
}
type EdgeType struct {
    Cursor int64
    Edge   NodeType
}

func (receiver EdgeType) TableName() string {
    return "connection_view"
}

由于这个单独不起作用,所以我尝试实现 Scanner/Value 接口。

不幸的是,Scan 根本没有通过以下调用执行:

    connection := make([]EdgeType, 0)
    err := db.GormDB.Find(&connection).Error

这导致了我的下一个问题:如果我的 Scan/Value 函数没有被调用,我将无法调试它们。我已经看到 another answer 几乎描述了我的问题,但优势在于能够将 Child 类型映射到 postgres 中的特定 geolocation 类型。

func (receiver *NodeType) Scan(src interface{}) error {
    // raw := src.(string)
    // fmt.Printf("raw: %s", raw)
    // maybe parse the src string and set parsed data to receiver?
    return nil
}

func (receiver NodeType) Value() (driver.Value, error) {
    // what to return for multiple fields?
    return receiver, nil
}

我可以在我的 Value 方法中返回什么来一次处理多个字段?或者:这甚至可能/受支持吗?我是否错误地声明了 Scan 函数或为什么没有调用它?

【问题讨论】:

  • 你试过使用结构标签吗?即Edge NodeType `gorm:"embedded"`。在此处阅读更多信息:gorm.io/docs/models.html#Embedded-Struct
  • 天啊。是的,就像一个魅力。
  • 顺便说一下,就 Scan/Value 而言,它们旨在读取/写入单个列,即给 Scan 的 src 将始终表示单个表列,并且返回值来自值将始终用于分配单个列。

标签: postgresql go go-gorm


【解决方案1】:

正如 mkopriva 指出的那样,有一个 gorm:"embedded" 标签。

type NodeType struct {
    ID     int64
    Text   string
    UserID int64
}

type EdgeType struct {
    Cursor int64
    Edge   NodeType `gorm:"embedded"`
}

这无需任何扫描/值函数即可工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2019-12-13
    • 1970-01-01
    相关资源
    最近更新 更多