我有一个Go结构,其中包含一片字符串,我想将其保存为带有GORM的Postgres中的jsonB对象。
我遇到了一个需要使用我想避免的特定于GORM的类型(postgres.Jsonb)的解决方案。
当我尝试在模型中使用 slice 运行AutoMigrate时,它会死机并且无法启动,尽管当我将 slice 包装在结构中(我可以做)时,它将自动运行但不会创建列在postgres中。
type User struct {
gorm.Model
Data []string `sql:"type:"jsonb"; json:"data"`
} //Panics
type User struct {
gorm.Model
Data struct {
NestedData []string
} `sql:"type:"jsonb"; json:"data"`
} //Doesn't crash but doesn't create my column
没有人能够在模型中不使用postgres.Jsonb类型使用GORM操作jsonb吗?
最佳答案
可能是:
type DataJSONB []string
func (dj DataJSONB) Value() (driver.Value, error) {
return json.Marshal(dj)
}
func (dj *DataJSONB) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
return fmt.Errorf("[]byte assertion failed")
}
return json.Unmarshal(b, dj)
}
// Your bit
type User struct {
gorm.Model
Data DataJSONB `sql:"type:"jsonb"; json:"data"`
}
关于postgresql - []使用Gorm和Postgres转换为jsonb的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60092840/