3 回答
TA贡献1752条经验 获得超4个赞
只需在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)
}
->元帅的参考链接,Unmarshal
现在您可以使用以下命令插入数据DB.Create(&yourTableName)
TA贡献1772条经验 获得超6个赞
我在 https://stackoverflow.com/a/71636216/13719636 中回答了类似的问题。
在 Gorm 中使用 JSONB 的最简单方法是使用 .pgtype.JSONB
Gorm 使用作为驱动程序,并具有名为 的包,其类型名为 。pgxpgxpgtypepgtype.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)
- 3 回答
- 0 关注
- 281 浏览
添加回答
举报
