How to insert Data in JSONB Fiel
2024-04-22 本文已影响0人
夜空最亮的9星
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"`
}