3 回答

TA貢獻1772條經驗 獲得超6個贊
只需在 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的參考鏈接
現在您可以使用插入數據DB.Create(&yourTableName)

TA貢獻1844條經驗 獲得超8個贊
我在https://stackoverflow.com/a/71636216/13719636中回答了類似的問題。
在 Gorm 中使用 JSONB 的最簡單方法是使用pgtype.JSONB.
Gorm 使用pgx它作為驅動程序,并且pgx具有名為 的包pgtype,其類型為pgtype.JSONB。
如果您已經pgx按照 Gorm 的指示安裝,則不需要安裝任何其他軟件包。
此方法應該是最佳實踐,因為它使用底層驅動程序并且不需要自定義代碼。
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 關注
- 348 瀏覽
添加回答
舉報