Gorm 扫描嵌套结构

Gorm Scan Nested Structs

我正在尝试使用 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 函数没有被调用,我将无法调试它们。我已经看到 几乎描述了我的问题,但优势是能够将 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
}

我可以 return 在我的 Value 方法中使用什么来同时处理多个字段?或者:甚至 possible/supported?我是否错误地声明了 Scan 函数,或者为什么没有调用它?

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

type NodeType struct {
    ID     int64
    Text   string
    UserID int64
}

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

这没有任何 Scan/Value 功能。