【问题标题】:Use a unix timestamp for UpdatedAt field in gorm在 gorm 中为 UpdatedAt 字段使用 unix 时间戳
【发布时间】:2020-07-11 10:40:03
【问题描述】:

我正在编写一个使用 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"

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    如果您想将 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 中函数的签名以决定如何调用该函数。

    【讨论】:

    • 仍然在查询中传递日期时间字符串而不是时间戳?
    • 这仍然是用 gorm 存储时间戳的最佳方式吗???
    猜你喜欢
    • 1970-01-01
    • 2010-12-31
    • 2019-10-14
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多