Search code examples
gogo-gorm

Gorm Timestamps in Golang


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"`
}

If I pass some values to created_at and updated_at it is taking up the current time as a default value and not taking up the value that I have passed. Is there any way I can make the gorm take up the values that I have passed.


Solution

  • Three ways

    1. Define default tag for field with a database function to fill in the default. e.g. for MySQL database current_timestamp() can be used
         CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP()"`
    
    1. Assign default values as suggested by @Guolei.
    2. Embed gorm.Model in your struct instead, for automatic handling of ID, CreatedAt, UpdatedAt and DeletedAt.