登录
首页 >  Golang >  Go问答

postgres 的 sql 类型(映射)无效

来源:stackoverflow

时间:2024-04-11 20:42:31 187浏览 收藏

本篇文章给大家分享《postgres 的 sql 类型(映射)无效》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我正在尝试使用 gorm 将嵌套结构保存到 postgres 中,但我的 map[string]*innerstruct 类型遇到了一些问题。

我想将我的地图类型存储为 postgres 中的 jsonb,因此我定义了一个扫描器/评估器,如类似问题中所建议的那样:

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:postgres 的 sql 类型 somemaptype(映射)无效 [已恢复]

看起来这种情况甚至在调用我的 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"`
}

今天关于《postgres 的 sql 类型(映射)无效》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>