当前位置: > > > > 对 gorm 中的 UpdatedAt 字段使用 unix 时间戳
来源:stackoverflow
2024-04-19 17:24:35
0浏览
收藏
小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《对 gorm 中的 UpdatedAt 字段使用 unix 时间戳》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!
问题内容
我正在编写一个使用 gorm orm 与 sqlite3
数据库通信的应用程序。现在的问题是我需要将 updatedat
列设置为 unix 时间戳,因为另一个遗留应用程序正在使用相同的数据库,并且它们应该兼容。
因此,我尝试使用以下代码块在 beforeupdate
挂钩上使用 unix 时间戳更新 updatedat
字段。
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
没有很好的文档记录,因此您必须阅读代码才能了解其工作原理,即 行调用上面的 beforeupdate()
函数。
正如您在 函数中看到的,它检查 switch
中函数的签名来决定如何调用该函数。
以上就是《对 gorm 中的 UpdatedAt 字段使用 unix 时间戳》的详细内容,更多关于的资料请关注公众号!