美文网首页
How to insert Data in JSONB Fiel

How to insert Data in JSONB Fiel

作者: 夜空最亮的9星 | 来源:发表于2024-04-22 16:40 被阅读0次

How to insert Data in JSONB Field of Postgres using GORM

Just add this below code in YourModel.go

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)
}

type YourModel struct {
   Name             string `gorm:"type:varchar(50)" json:"name"`
   Email            string `gorm:"type:varchar(50)" json:"email"`
   FirstImgs    JSONB    `gorm:"column:first_imgs" json:"first_imgs"`
   SecondImgs   JSONB    `gorm:"column:second_imgs" json:"second_imgs"`
}

参考连接:
https://stackoverflow.com/questions/65434115/how-to-insert-data-in-jsonb-field-of-postgres-using-gorm

相关文章

网友评论

      本文标题:How to insert Data in JSONB Fiel

      本文链接:https://www.haomeiwen.com/subject/vifixjtx.html