go - 在 gorm 中为 UpdatedAt 字段使用 unix 时间戳

标签 go go-gorm

我正在编写一个与 sqlite3 通信的应用程序使用 GORM ORM 的数据库。现在问题是我需要制作 UpdatedAt列一个unix时间戳,因为另一个遗留应用程序正在使用相同的数据库并且它们应该是兼容的。

所以我尝试更新 UpdatedAt BeforeUpdate 上带有 unix 时间戳的字段使用以下代码块 Hook 。

func (c *CartItems) BeforeUpdate() (err error) {
    fmt.Println("----------------------------------------")
    fmt.Println("BeforeUpdate")
    fmt.Println( c )
    c.UpdatedAt = time.Now().Unix()
    fmt.Println("----------------------------------------")
    return
}

但是当我运行代码查询时保持不变并且没有将时间戳添加到数据库中。

格姆日志
----------------------------------------
BeforeUpdate
&{55 21 4 7 1585607114 1585607114 {0 [] [] [] {0 0 } 0 0} {0  0 0 0}}
----------------------------------------

[2020-03-31 04:30:02]  [0.46ms]  UPDATE "cart_items" SET "quantity" = 7, "updated_at" = '2020-03-31 04:30:02'  WHERE "cart_items"."id" = 55  
[1 rows affected or returned ] 
[GIN] 2020/03/31 - 04:30:02 | 200 |   97.963597ms |       127.0.0.1 | POST     "/cache/cart/21/item"

最佳答案

如果您想拥有 UpdatedAt(),请使用以下命令和 CreatedAt()作为unix时间戳。

type CartItems struct {
    CreatedAt int64
    UpdatedAt int64
}

func (m *CartItems) BeforeUpdate(scope *gorm.Scope) error {
    scope.SetColumn("UpdatedAt", time.Now().Unix())
    return nil
}

func (m *CartItems) BeforeCreate(scope *gorm.Scope) error {
    if m.UpdatedAt == 0 {
        scope.SetColumn("UpdatedAt", time.Now().Unix())
    }

    scope.SetColumn("CreatedAt", time.Now().Unix())
    return nil
}

不幸的是,gorm没有很好的文档记录,因此您必须阅读代码以了解其工作原理,即 this线路调用上述BeforeUpdate()功能。

正如您在 callMethod() 中看到的那样函数,它检查 switch 中函数的签名决定如何调用该函数。

关于go - 在 gorm 中为 UpdatedAt 字段使用 unix 时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60941097/

相关文章:

go - 接口(interface)的同义结构字段和方法名称

go - 如何解码 base64 字符串并获得包括重音符号在内的正确字符?

postgresql - 如何使用gorm包从golang调用postgres存储过程

sql-server - MS SQL 限制选项不起作用

go - K8s算子读取原始数据

go - 使用 Go 的接收和发送 TCP 客户端

database - 在一个查询中获取结构和其他数据

sql - 为什么在 gorm 等 go 库中使用 struct 中的 sql 标签?

mysql - 从 GORM 中检索多对多结果

ruby - Rust 数学错误