[]使用Gorm和Postgres转换为jsonb的字符串 [英] []string to jsonb with Gorm and postgres
问题描述
我有一个Go结构,其中包含一片字符串,我想将其保存为带有GORM的Postgres中的jsonB对象.
I have a Go struct which contains a slice of strings which I'd like to save as a jsonB object in Postgres with GORM.
我遇到了一个解决方案,该解决方案要求使用我要避免的GORM特定类型(postgres.Jsonb).
I've come accross a solution which requires to use the GORM specific type (postgres.Jsonb) which I'd like to avoid.
当我尝试在模型中使用切片运行AutoMigrate时,它会死机并且无法启动,尽管当我将此切片包装在结构中(我可以做)时,它将自动运行但不会出错在postgres中创建列.
When I try to run the AutoMigrate with a slice in my model, it panics and won't start although when I wrap this slice in a struct (which I'm okay doing) it will run without error but won't create the column in 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吗?
Has anyone been able to manipulate jsonb with GORM without using the postgres.Jsonb type in models ?
推荐答案
也许:
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"`
}
这篇关于[]使用Gorm和Postgres转换为jsonb的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!