首页 > 解决方案 > 使用 GORM 保存时间戳适用于 SQLite,但不适用于 Postgres

问题描述

这是我的模型:

type Event struct {
SessionId string    `gorm:"type:uuid;primary_key;not null"`
Received  int64     `gorm:"type:timestamp;primary_key;not null"`
EventType EventType `gorm:"primary_key;not null"`
UserId    string    `gorm:"type:uuid"`
GameId    string
Story     string
}

如果我使用 SQLite,“接收”时间戳将正确存储为 Unix 时间戳。但是,使用 Postgres 驱动程序,我得到:

 pq: date/time field value out of range: "1593187082040"

标签: postgresqlgo-gorm

解决方案


原来这type:timestamp需要 time.Time 而不是 int64。为了解决这个问题,我必须将字段类型更改为 time.Time 并解析时间戳。但是,由于时间戳值以“ms”为单位,因此在 Go 中解析它有点棘手:

time.Unix(0, 1593187082040*int64(time.Millisecond))

推荐阅读