Upsert with attribute included updated_at

Viewed 1613

I want to make some script backfill data from an old database to a new database, with gorm as it ORM, and I want to upsert using FirstOrCreate, below are the attributes and query used:

user {
  ID: someid,
  Name: somename,
  .
  .
  .
  CreatedAt: time.Time,
  UpdatedAt: 2020-03-24 17:57:00,
}

err = db.Where(user{ID: someid}).Assign(user).FirstOrCreate(&user)

I want in new database, the data is as it is (updated_at = 2020-03-24 17:57:00) but I got updated_at is time.Now()

How can I upsert the data with updated_at is updated as I send it?

1 Answers

FirstOrCreate() calls Updates() when data exist with given ID. Updates() operation will perform the model's BeforeUpdate, AfterUpdate method, update its UpdatedAt timestamp, save its Associations when updaing, if you don't want to call them, you could use UpdateColumn, UpdateColumns with separate Create operation when data is not exist.

Ref: Gorm official document about update

Related