postgresql - 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 类型映射到geolocation
postgres 中的特定类型。
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"`
}
这在没有任何扫描/值功能的情况下有效。
推荐阅读
- java - 从列表中动态创建 Tablayout 中的选项卡?
- datetime - 雪花 GMT 字符串到日期转换
- c# - EF Core Distinct + OrderBy 引发翻译错误
- python - 获取基于另一列的分组值的百分比pands python
- c# - to当我的方法没有返回值时如何使用out参数
- flutter - Flutter web 中是否有相当于 `overflow:scroll` 的功能?
- python - 如何在 Pandas 数据框的每一行中获取包含值的预定义等价类名称的列?
- java - 如何将 Java `Consumer` 转换为 Groovy `Closure`?
- javascript - 使用 Vue.js + axios 将本地图像链接到 api 数组
- types - 系统 Verilog 枚举类型分配