Gorm 使用自动更新时间

背景

  • 在Mysql中有这样的一个功能,就是当表中的一条记录更新时,可以创建一个时间字段,也自动更新。
  • Mysql 文档中给的例子如下
CREATE TABLE test_t1 (
  id int,
  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  dt DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
  • 插入如一条数据
  • 然后更新一条数据
MySQL root@(none):sports> select * from test_t1;
+----+---------------------+---------------------+
| id | ts                  | dt                  |
+----+---------------------+---------------------+
| 12 | 2022-04-01 18:12:18 | 2022-04-01 18:12:18 |
+----+---------------------+---------------------+

## 更新数据
MySQL root@(none):sports> update test_t1 set id = id + 1 where id = 12;
Query OK, 1 row affected
Time: 0.009s
MySQL root@(none):sports> select * from test_t1;
+----+---------------------+---------------------+
| id | ts                  | dt                  |
+----+---------------------+---------------------+
| 13 | 2022-04-01 19:49:17 | 2022-04-01 19:49:17 |
+----+---------------------+---------------------+
1 row in set
Time: 0.007s
  • 可以看到ts和dt两个字段更新了,更新为在更新的时候的时间。
  • 在gorm里也可以实现这个功能

Gorm实现更新记录时间

  • 需要使用标签type:TIMESTAMP;default:CURRENT_TIMESTAMP on update current_timestamp
  • 值得注意的是,需要指定type以及default语句
func main() {

    initDB() // 初始化db
    m := RelatedTime{
        ContentId: "123",
        MatchName: "match_name6",
    }
    db.Clauses(clause.OnConflict{
        UpdateAll: true,
    }).Create(&m)
    fmt.Printf("%+v\n", m)
    m = RelatedTime{}
    db.Where("content_id = ?", "123").Find(&m)
    fmt.Println(m)
}

type RelatedTime struct {
    ID        int       `json:"id"`
    MatchName string    `gorm:"column:match_name;type:varchar(128)" json:"match_name,omitempty"`
    ContentId string    `gorm:"column:content_id;type:varchar(128);uniqueIndex:by_content_id" json:"content_id,omitempty"`
    CreatedAt time.Time `gorm:"column:created_at;type:TIMESTAMP;default:CURRENT_TIMESTAMP;<-:create" json:"created_at,omitempty"`
    UpdateAt  time.Time `gorm:"column:update_at;type:TIMESTAMP;default:CURRENT_TIMESTAMP  on update current_timestamp" json:"update_at,omitempty"`
}

mysql> select * from related_times ;
+----+-------------+------------+---------------------+---------------------+
| id | match_name  | content_id | created_at          | update_at           |
+----+-------------+------------+---------------------+---------------------+
|  1 | match_name6 | 123        | 2022-04-01 18:24:35 | 2022-04-01 19:35:08 |
+----+-------------+------------+---------------------+---------------------+
1 row in set (0.00 sec)

  • 执行之后会看到字段UpdateAt更新了,而CreatedAt还保持不变
  • 为什么需要UpdateAt这样的字段?有的时候,在更新记录是没有记录日志,可以作为一个更新的标记,在查问题或者查看数据更新的时间的时候能够使用到。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容