gorm 如何声明不自动更新的 unix 时间戳 mills 字段

问题描述 投票:0回答:1

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

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纪元时间中存储最多毫秒。我当然可以将其声明为 int64,然后尝试手动填充正确的值。

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

go unix-timestamp go-gorm
1个回答
0
投票

据我所知,您可以创建一个嵌入 time.Time 的自定义类型并覆盖其 Scan 和 Value 方法来处理数据库表示(int64)和 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
}

然后,在您的 GORM 模型中,您可以使用此自定义类型作为时间戳字段:

type YourModel struct {
    ID        uint         `gorm:"primaryKey"`
    Timestamp UnixTimestamp
    // ...
}

每当您查询或保存记录时,gorm 都会自动处理转换数据

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

© www.soinside.com 2019 - 2024. All rights reserved.