gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:07:08 24 4
gpt4 key购买 nike

我正在编写一个与 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com