首页 > 解决方案 > Gorm 扫描嵌套结构

问题描述

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

该视图包含 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 类型映射到geolocationpostgres 中的特定类型。

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 函数或为什么不调用它?

标签: postgresqlgogo-gorm

解决方案


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

type NodeType struct {
    ID     int64
    Text   string
    UserID int64
}

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

这在没有任何扫描/值功能的情况下有效。


推荐阅读