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.
CodePudding user response:
if containing fileds: CreatedAt and UpdatedAt, gorm will use reflect to insert default value when executing. also you could give the specific value.
info := Example{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
_, err := DB.Insert(info)
CodePudding user response:
Three ways
- 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()"`
- Assign default values as suggested by @Guolei.
- Embed
gorm.Model
in your struct instead, for automatic handling of ID, CreatedAt, UpdatedAt and DeletedAt.