我正在尝试使用 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/