插件窝 干货文章 使用 Gorm 新增数据时遇到 “Unknown column 'created_at' in 'field list'” 错误,如何解决?

使用 Gorm 新增数据时遇到 “Unknown column 'created_at' in 'field list'” 错误,如何解决?

字段 time Gorm 禁用 888    来源:    2025-03-31

解决 Gorm 中的 "Unknown column 'created_at'" 错误

这个错误通常发生在使用 Gorm 进行数据库操作时,Gorm 默认期望表中有 created_atupdated_at 时间戳字段,但你的表中可能没有这些字段。

解决方案

方法1:禁用自动时间戳跟踪

// 在模型定义中禁用时间戳跟踪
type YourModel struct {
    // 你的字段...
    CreatedAt time.Time `gorm:"-"`
    UpdatedAt time.Time `gorm:"-"`
}

// 或者在初始化时全局禁用
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
    SkipDefaultTransaction: true,
    NowFunc: func() time.Time {
        return time.Now().Local()
    },
    DisableAutomaticTimeStamp: true, // 禁用自动时间戳
})

方法2:添加时间戳字段到表

type YourModel struct {
    ID        uint `gorm:"primaryKey"`
    // 其他字段...
    CreatedAt time.Time
    UpdatedAt time.Time
    // 如果有软删除需求
    DeletedAt gorm.DeletedAt `gorm:"index"`
}

然后确保你的数据库表中有相应的列:

ALTER TABLE your_table ADD COLUMN created_at DATETIME;
ALTER TABLE your_table ADD COLUMN updated_at DATETIME;

方法3:自定义时间戳字段名

type YourModel struct {
    ID         uint `gorm:"primaryKey"`
    // 其他字段...
    CreateTime time.Time `gorm:"column:create_time"` // 自定义列名
    UpdateTime time.Time `gorm:"column:update_time"` // 自定义列名
}

方法4:临时解决方案(不推荐)

db.Session(&gorm.Session{SkipHooks: true}).Create(&yourModel)

最佳实践

  1. 推荐使用方法2:添加标准的时间戳字段到你的表和模型中,这符合 Gorm 的约定并提供了有用的元数据
  2. 如果你确实不需要这些字段,使用方法1明确禁用它们
  3. 确保数据库迁移脚本与模型定义保持同步

这个错误表明你的数据库表结构与 Gorm 模型定义不完全匹配,解决的关键是确保两者一致。