Golang 中的 Gorm 时间戳

Sum*_*rma 0 go go-gorm

type Base struct {
    ID          uint            `gorm:"primary_key" json:"id"`
    CreatedAt   time.Time       `json:"created_at"`
    UpdatedAt   time.Time       `json:"updated_at"`
    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"`
}
Run Code Online (Sandbox Code Playgroud)

如果我将一些值传递给created_at和updated_at,它会将当前时间作为默认值,而不是我传递的值。有什么办法可以让 gorm 接受我已经传递的价值观吗?

小智 8

三种方式

  1. 使用数据库函数定义字段的默认标记以填充默认值。例如对于MySQL数据库可以使用current_timestamp()
     CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP()"`
Run Code Online (Sandbox Code Playgroud)
  1. 按照@Guolei 的建议分配默认值。
  2. 相反,嵌入gorm.Model到您的结构中,以自动处理 ID、CreatedAt、UpdatedAt 和 DeletedAt。