Gorm 使用自动更新时间

2022-04-01  本文已影响0人  别时茫茫

背景

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

Gorm实现更新记录时间

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)

上一篇 下一篇

猜你喜欢

热点阅读