postgresql - postgres 的 sql 类型(映射)无效

标签 postgresql go jsonb go-gorm

我正在尝试使用 gorm 将嵌套结构保存到 postgres 中,但我的 map[string]*InnerStruct 遇到了一些问题类型。
我想在 postgres 中将我的 map 类型存储为 JSONB,所以我定义了一个 Scanner/Valuer,就像在类似的 questions 中建议的那样:

type SomeMapType map[string]*InnerStruct

type StoreStruct struct {
    gorm.Model
    Id               string `gorm:"type:uuid;primary_key"`
    AccountID        string
    SomeMapType      SomeMapType `gorm:"column:cache,type:jsonb"`
}

var _ driver.Valuer = SomeMapType{}
var _ sql.Scanner = &SomeMapType{}

func (smt SomeMapType) Value() (driver.Value, error) {
    return json.Marshal(smt)
}

func (smt *SomeMapType) Scan(value interface{}) error {
    b, ok := value.([]byte)
    if !ok {
        return errors.New("type assertion to []byte failed")
    }

    return json.Unmarshal(b, &smt)
}

但是当我尝试像这样创建一个表时:
err := db.
        CreateTable(StoreStruct{}).
        Table(tableName).Error)
发生 panic :panic: invalid sql type SomeMapType (map) for postgres [recovered]看起来甚至在调用我的 Valuer/Scanner 实现之前就发生了这种情况。
是否无法存储 map你想用gorm保存到数据库的结构上的字段?
我相信我已经看到了似乎与 map[string]interface{} 一起使用的示例所以我不确定为什么我的情况不同?

最佳答案

我的问题不包括 SQL 类型标记注释。
进行以下更改解决了我的问题:

type StoreStruct struct {
    gorm.Model
    Id               string `gorm:"type:uuid;primary_key"`
    AccountID        string
    SomeMapType      SomeMapType `gorm:"column:cache" sql:"type:jsonb"`
}

关于postgresql - postgres 的 sql 类型(映射)无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63289749/

相关文章:

java - 无法通过反射/Spring-boot-devtools 设置字段值

postgresql - 如何在 pgAdmin 4 中显示错误?

python - 多条件有效查询

google-app-engine - Betfair 非交互式 (Bot) 登录在 Google App Engine 区域 eu-west2(伦敦)中不起作用

go - 更新 MS SQL 表

postgresql - 来自 jsonb 的 SQLAlchemy Pandas read_sql

postgresql - postgres9.4 循环通过 jsonb : how select vals of key:val pairs

postgresql - 在 Delphi 上使用 FireDAC 从 sql 表中获取文本 [] 值

ruby-on-rails - 导入 Rails 的 boolean 值

json - 是否可以在JSON中创建自定义对象键? [复制]