这个错误通常发生在使用 Gorm 进行数据库操作时,Gorm 默认期望表中有 created_at
和 updated_at
时间戳字段,但你的表中可能没有这些字段。
// 在模型定义中禁用时间戳跟踪
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, // 禁用自动时间戳
})
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;
type YourModel struct {
ID uint `gorm:"primaryKey"`
// 其他字段...
CreateTime time.Time `gorm:"column:create_time"` // 自定义列名
UpdateTime time.Time `gorm:"column:update_time"` // 自定义列名
}
db.Session(&gorm.Session{SkipHooks: true}).Create(&yourModel)
这个错误表明你的数据库表结构与 Gorm 模型定义不完全匹配,解决的关键是确保两者一致。