我有一个结构Huygens
type Huygens struct {
Worlds map[string]World `json:"worlds" sql:"type:JSONB"`
}
type World struct {
Diameter int
Name string
}当我尝试使用GORM插入到Postgres DB中时,我得到:
sql: converting argument $1 type: unsupported type map[string]huygens.world, a map要插入,我只需使用db.Create(&World{})
有人知道如何将该列作为JSONB列插入并避免该错误吗?
谢谢
发布于 2021-08-26 22:11:43
您需要将Huygens指定为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)})你可以看到更多的here。
发布于 2021-08-27 10:41:52
另一种使模型更有用的方法是创建一个实现Scan/Value的类型,并在这些类型中从/Marshal解组到JSON:
type Huygens struct {
Worlds WorldsMap `json:"worlds"`
}
type World struct {
Diameter int
Name string
}
type WorldsMap map[string]World
func (WorldsMap) GormDataType() string {
return "JSONB"
}
func (w *WorldsMap) Scan(value interface{}) error {
var bytes []byte
switch v := value.(type) {
case []byte:
bytes = v
case string:
bytes = []byte(v)
default:
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
}
err := json.Unmarshal(bytes, w)
return err
}
func (w WorldsMap) Value() (driver.Value, error) {
bytes, err := json.Marshal(s)
return string(bytes), err
}然后,您可以在代码中像使用映射一样使用Worlds字段,而不是笨拙的字节切片。
https://stackoverflow.com/questions/68944128
复制相似问题