首页 > 解决方案 > 如何将地图 [字符串] 插入 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 列并避免该错误?

谢谢

标签: postgresqlgogo-gorm

解决方案


您需要指定它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)})

你可以在这里看到更多。


推荐阅读