正如我所知,您可以创建一个自定义类型,该类型嵌入time.Time并重写其Scan和Value方法,以处理数据库表示形式(int 64)和Go表示形式(time.Time)之间的转换.
以下是您可以为您的Unix时间戳字段定义自定义类型的方法:
import (
"database/sql/driver"
"time"
)
// Define custom type to represent Unix timestamp in milliseconds
type UnixTimestamp struct {
time.Time
}
// Scan converts the database field to UnixTimestamp type
func (u *UnixTimestamp) Scan(value interface{}) error {
if value == nil {
return nil
}
unixTime := value.(int64) / 1000 // value is in ms
u.Time = time.Unix(unixTime, 0)
return nil
}
// Value converts UnixTimestamp type to a value that can be stored in the database
func (u UnixTimestamp) Value() (driver.Value, error) {
if u.IsZero() {
return nil, nil
}
return u.UnixNano() / int64(time.Millisecond), nil
}
然后,在您的SEARCH模型中,您可以将此自定义类型用于您的时间戳字段:
type YourModel struct {
ID uint `gorm:"primaryKey"`
Timestamp UnixTimestamp
// ...
}
每当您查询或保存记录时,gorm都会自动处理转换数据
抱歉我的英语不好,我希望这能有所帮助