You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Golang的Gorm框架采用自定义的CreatedAt/UpdatedAt值

解决Gorm忽略自定义CreatedAt/UpdatedAt时间值的问题

Gorm默认会自动为CreatedAt和UpdatedAt字段填充当前系统时间,这就是你的自定义时间值被覆盖的原因。以下是几种可行的解决方法:

方法一:在模型级别关闭自动时间填充

直接修改你的Base结构体,给目标字段添加gorm:"autoCreateTime:false"和gorm:"autoUpdateTime:false"标签,禁用Gorm的自动填充逻辑,这样传入的自定义时间会被直接写入数据库:

type Base struct {
    ID          uint            `gorm:"primary_key" json:"id"`
    CreatedAt   time.Time       `json:"created_at" gorm:"autoCreateTime:false"`
    UpdatedAt   time.Time       `json:"updated_at" gorm:"autoUpdateTime:false"`
    DeletedAt   *gorm.DeletedAt `sql:"index" json:"deleted_at" swaggertype:"primitive,string"`
    CreatedByID uint            `gorm:"column:created_by_id" json:"created_by_id"`
    UpdatedByID uint            `gorm:"column:updated_by_id" json:"updated_by_id"`
}

方法二:全局关闭自动时间戳

如果你的整个项目都不需要Gorm自动维护时间字段,可以在初始化数据库连接时配置DisableAutomaticTimeStamp: true,全局禁用自动时间填充:

import (
  "gorm.io/driver/sqlite"
  "gorm.io/gorm"
)

func initDB() (*gorm.DB, error) {
  db, err := gorm.Open(sqlite.Open("your_db.db"), &gorm.Config{
    DisableAutomaticTimeStamp: true,
  })
  return db, err
}

方法三:个别操作手动指定字段(保留全局自动填充)

如果只是部分场景需要自定义时间,其他场景保持自动填充,可以在创建或更新操作时,用Select明确指定要写入的字段,强制Gorm使用你传入的值:

创建记录时

import "time"

// 自定义时间
customCreatedAt := time.Date(2024, 5, 20, 10, 0, 0, 0, time.UTC)
customUpdatedAt := time.Date(2024, 5, 20, 10, 0, 0, 0, time.UTC)

// 实例化模型
baseModel := Base{
  CreatedAt:   customCreatedAt,
  UpdatedAt:   customUpdatedAt,
  CreatedByID: 1,
  UpdatedByID: 1,
}

// 明确指定要插入的字段,包含CreatedAt和UpdatedAt
db.Select("CreatedAt", "UpdatedAt", "CreatedByID", "UpdatedByID").Create(&baseModel)

更新记录时

customUpdatedAt := time.Date(2024, 5, 21, 14, 30, 0, 0, time.UTC)

// 用UpdateColumn直接更新字段,绕过自动时间逻辑
db.Model(&baseModel).UpdateColumn("UpdatedAt", customUpdatedAt)

// 或者用Select指定字段更新
db.Model(&baseModel).Select("UpdatedAt").Update("UpdatedAt", customUpdatedAt)

内容的提问来源于stack exchange,提问作者Sumit Vishwakarma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 18:58:06