Reputation: 195
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.
Upvotes: 2
Views: 15606
Reputation: 167
I think the gorm.Model now automatically import the created_at, updated_at, and deleted_at on 2023. Here is my model
Upvotes: 1
Reputation: 120
An update to @s3vt's answer:
If you the first method they provided, you need to put the function without the parenthesis like this:
CreatedAt time.Time `gorm:"default:current_timestamp"`
I spent a lot of time trying to figure out the error I was getting so I thought I'd share it for the people who might face this!
Upvotes: 3
Reputation:
Three ways
current_timestamp()
can be used CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP()"`
gorm.Model
in your struct instead, for automatic handling of ID, CreatedAt, UpdatedAt and DeletedAt.Upvotes: 10
Reputation: 145
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)
Upvotes: 1