Your Question
My business entity already has a updated_at that I perform business logic on, I want to disable gorm's auto-updating on that field globally. Is there a way to do that? I know when updating, I can use UpdateColumns to avoid updated_at being updated. But for other queries, like on conflict, I can't find a way to disable it.
I tried to set Session's skipHooks to be true, but that still doesn't work. For example:
type Organization struct {
ID string `json:"id"`
Name string `json:"name"`
IsArchived bool `json:"isArchived"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
result := o.db.orm.Model(&organization).Session(&gorm.Session{SkipHooks: true}).Clauses(clause.OnConflict{
Where: clause.Where{Exprs: []clause.Expression{clause.Lt{Column: "organizations.updated_at", Value: organization.UpdatedAt}}},
UpdateAll: true,
}).Create(&organization)
This still generates SQL:
INSERT INTO "organizations"
(
"id",
"name",
"is_archived",
"created_at",
"updated_at"
)
VALUES
(
'123456789',
'Test',
TRUE,
'2021-06-11 00:52:20.65',
'2021-06-13 16:13:58.309'
)
on conflict
(
"id"
)
DO
UPDATE
SET "updated_at"='2021-11-03 07:56:17.547',
"name"="excluded"."name",
"is_archived"="excluded"."is_archived"
WHERE "organizations"."updated_at" < '2021-06-13 16:13:58.309'
I want SET "updated_at"="excluded"."updated_at" instead of "updated_at"='2021-11-03 07:56:17.547'
using the version v1.22.1 with Postgres.
The document you expected this should be explained
https://gorm.io/docs/session.html https://gorm.io/docs/write_plugins.html
Expected answer
A way to disable auto updated_at globally.
Comment From: jinzhu
rename field name UpdatedAt to something different, the column name could still use updated_at
Comment From: dovefi
use UpdateColumns() instead!!! it work
Comment From: eriknyk
We should to be able to disable autoCreateTime and autoUpdateTime globally through gorm.Config{}
Comment From: puripat-hugeman
Use tag autoUpdateTime:false
Example:
type YourModel struct {
ID uuid.UUID `gorm:"column:id"`
UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime:false"`
}
Comment From: eriknyk
Yeap! However the idea of a global way to disable it is when you have lot of structs in my places and add the tag to each struct type is not an option.