postgresql - []使用Gorm和Postgres转换为jsonb的字符串

标签 postgresql go jsonb go-gorm

我有一个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操作j​​sonb吗?

最佳答案

可能是:

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/

相关文章:

postgresql - 如何从 Postgres jsonb 对象中删除一组键?

c# - 如何将 NpgsqlCopyIn 与 NpgsqlCopySerializer 一起使用?

linux - 在单个 IP 上维护超过 65535 个连接

http - 在 Go 中构建 URL,包括服务器方案

postgresql - 如何为模糊和右 anchor 搜索索引 PostgreSQL JSONB 平面文本数组?

postgresql - Postgres jsonb_set 连接当前值

postgresql - 如何避免在第一次运行时使用 Doctrine 2 Migrations diff 的 DROP DEFAULT 语句?

sql - sql中的自定义排序

pandas - 删除编码 "UTF8": 0x00 chars from pandas dataframe for psycopg2 cursor

go - 规范 : What's the purpose of the blank identifier in variable assignment?