如何使用 GORM 在 Postgres 的 JSONB 字段中插入数据

How to insert Data in JSONB Field of Postgres using GORM

我在

中有这样的模型
type yourTableName struct {
   Name             string `gorm:"type:varchar(50)" json:"name"`
   Email            string `gorm:"type:varchar(50)" json:"email"`
   FieldNameOfJsonb JSONB  `gorm:"type:jsonb" json:"fieldnameofjsonb"`
}
{
    "name": " james",
    "email": "james@gmail.com",
    "FieldNameOfJsonb": [
        {
            "someField1": "value",
            "someFiedl2": "somevalue",    
        },
        {
            "Field1": "value1",
            "Fiedl2": "value2",
        }
    ],

只需在 Model.go (referenceLink)

中添加以下代码

import (
    "errors"
    "database/sql/driver"
    "encoding/json"
)

// JSONB Interface for JSONB Field of yourTableName Table
type JSONB []interface{}

// Value Marshal
func (a JSONB) Value() (driver.Value, error) {
    return json.Marshal(a)
}

// Scan Unmarshal
func (a *JSONB) Scan(value interface{}) error {
    b, ok := value.([]byte)
    if !ok {
        return errors.New("type assertion to []byte failed")
    }
    return json.Unmarshal(b,&a)
}

-> Marshal, Unmarshal

参考 Link
  • 现在您可以使用 DB.Create(&yourTableName)
  • 插入数据

您可以使用 gorm-jsonb 包。

我在 中回答了类似的问题。

在 Gorm 中使用 JSONB 的最简单方法是使用 pgtype.JSONB.

Gorm 使用 pgx 作为它的驱动程序,并且 pgx 有一个名为 pgtype 的包,其类型名为 pgtype.JSONB.

如果您已经按照 Gorm 的指示安装了 pgx,则不需要安装任何其他软件包。

这种方法应该是最佳实践,因为它使用底层驱动程序并且不需要自定义代码。

type User struct {
    gorm.Model
    Data pgtype.JSONB `gorm:"type:jsonb;default:'[]';not null"`
}

从数据库中获取值

u := User{}
db.find(&u)

var data []string

err := u.Data.AssignTo(&data)
if err != nil {
    t.Fatal(err)
}

将值设置为 DB

u := User{}

err := u.Data.Set([]string{"abc","def"})
if err != nil {
    return
}

db.Updates(&u)