postgresql - 如何将地图 [字符串] 插入 jsonb 字段
问题描述
我有一个结构Huygens
:
type Huygens struct {
Worlds map[string]World `json:"worlds" sql:"type:JSONB"`
}
type World struct {
Diameter int
Name string
}
当我尝试使用 GORM 插入 Postgres 数据库时,我得到:
sql: converting argument $1 type: unsupported type map[string]huygens.world, a map
要插入,我只需使用db.Create(&World{})
有谁知道如何将该列插入为 JSONB 列并避免该错误?
谢谢
解决方案
您需要指定它Huygens
是 a并将您的结构gorm.Model
转储为一个类型。World
[]byte
import (
"encoding/json"
"fmt"
"gorm.io/datatypes"
)
type Huygens struct {
gorm.Model
Worlds datatypes.JSON
}
type World struct {
Diameter int
Name string
}
world := World{Diameter: 3, Name: Earth}
b, err := json.Marshal(world)
if err != nil {
fmt.Println("error:", err)
}
db.Create(&Huygens{Worlds: datatypes.JSON(b)})
你可以在这里看到更多。
推荐阅读
- powershell - WindowsPowerShell 重命名项目
- java - java / scala不兼容的类型,当将scala类封装(或使用instanceof)到java类时,即使scala类扩展了java类
- php - 未定义的数组键 - Laravel/Fortify 寄存器
- laravel - 传递给 Laravel 中视图的测试变量
- python - 使用 Matplotlib 在两行之间着色
- cassandra - Cassandra:在多个节点关闭的情况下提示切换
- android - Firebase 实时数据库在连接不良时重复原子 ServerValue.increment
- matlab - 运行时检测到分段违规
- flutter - 在 Flutter 中绘制 3D 散点图
- nix - 如何使用 Nix 指定包/派生运行时依赖项?