Sumit Vishwakarma
Sumit Vishwakarma

Reputation: 195

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.

Upvotes: 2

Views: 15606

Answers (4)

Danendra
Danendra

Reputation: 167

I think the gorm.Model now automatically import the created_at, updated_at, and deleted_at on 2023. Here is my model

enter image description here

and here is the resultenter image description here

Upvotes: 1

Mirou
Mirou

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

user19812413
user19812413

Reputation:

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.

Upvotes: 10

Guolei
Guolei

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

Related Questions