登录
首页 >  Golang >  Go问答

Gorm 扫描嵌套结构

来源:stackoverflow

时间:2024-04-11 10:45:37 445浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《Gorm 扫描嵌套结构》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

我正在尝试使用 gorm 查询 golang 中的视图,并将结果保存在包含 nodetype 的结构 edgetype 中。 (基本上是尝试实现 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 类型映射到 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 函数,或者为什么没有调用它?


解决方案


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

type NodeType struct {
    ID     int64
    Text   string
    UserID int64
}

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

这无需任何扫描/值功能即可工作。

到这里,我们也就讲完了《Gorm 扫描嵌套结构》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>