我们在数据库表中有一个时间戳字段,它只应该在业务事件发生时更新,而不是在创建/每次更新时更新.

https://stackoverflow.com/a/60941397/41284处自动更新的例子,以及gorm官方文档中https://gorm.io/docs/models.html#Creating-x2F-Updating-Time-x2F-Unix-Milli-x2F-Nano-Seconds-Tracking处的例子,但我找不到一种方法来声明一个时间戳字段,存储时间为unix epoch时间,最多为毫秒.当然,我可以将其声明为int 64,然后try 手动填充正确的值.

还有其他更方便/自动化的 Select 吗?

推荐答案

正如我所知,您可以创建一个自定义类型,该类型嵌入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都会自动处理转换数据

抱歉我的英语不好,我希望这能有所帮助

Go相关问答推荐

正确使用pgtype的方法

什么东西逃到了堆里?

go aws-lambda 与 terraform 中的 exec 格式错误

将这两个函数合二为一的惯用方法

如何使用 html/template 在 golang 中运行一个范围内的范围

Go Gin:验证 base64

获取 nil 指针类型的 reflect.Value

Gremlin-Go:树步骤不可序列化

类型/ struct 函数的 GoDoc 示例函数

有没有办法约束(通用)类型参数?

如何在切片增长时自动将切片的新元素添加到函数参数

如何在切片增长时自动将切片的新元素添加到函数参数

具有两个或多个模型的 GORM 查询

具有未导出字段的 struct 类型之间的转换

通用函数与外部包中的常见成员一起处理不同的 struct ?

Terraform 自定义提供程序 - 数据源架构

Dynamodb.ScanInput - 不能使用expr.Names()(类型 map[string]*string)作为类型 map[string]string

如何使用 context.WithCancel 启动和停止每个会话的心跳?

(如何)我可以基于接口抽象地实现Stringer吗?

我应该明确地创建一个与Belongs To或Has Many对称的关系吗?