Skip to content

Commit c6ec172

Browse files
committed
Fix update UpdatedAt when full saving associations, close go-gorm#4115
1 parent 214f1ea commit c6ec172

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

callbacks/associations.go

+5
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,7 @@ func saveAssociations(db *gorm.DB, rel *schema.Relationship, values interface{},
361361
}
362362

363363
tx := db.Session(&gorm.Session{NewDB: true}).Clauses(onConflict).Session(&gorm.Session{
364+
FullSaveAssociations: db.FullSaveAssociations,
364365
SkipHooks: db.Statement.SkipHooks,
365366
DisableNestedTransaction: true,
366367
})
@@ -370,6 +371,10 @@ func saveAssociations(db *gorm.DB, rel *schema.Relationship, values interface{},
370371
return true
371372
})
372373

374+
if tx.Statement.FullSaveAssociations {
375+
tx = tx.InstanceSet("gorm:update_track_time", true)
376+
}
377+
373378
if len(selects) > 0 {
374379
tx = tx.Select(selects)
375380
} else if len(selectColumns) > 0 && len(omits) == 0 {

callbacks/create.go

+5
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,11 @@ func ConvertToCreateValues(stmt *gorm.Statement) (values clause.Values) {
320320
field.Set(stmt.ReflectValue, curTime)
321321
values.Values[0][idx], _ = field.ValueOf(stmt.ReflectValue)
322322
}
323+
} else if field.AutoUpdateTime > 0 {
324+
if _, ok := stmt.DB.InstanceGet("gorm:update_track_time"); ok {
325+
field.Set(stmt.ReflectValue, curTime)
326+
values.Values[0][idx], _ = field.ValueOf(stmt.ReflectValue)
327+
}
323328
}
324329
}
325330

tests/update_has_one_test.go

+11-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package tests_test
22

33
import (
44
"testing"
5+
"time"
56

67
"gorm.io/gorm"
78
. "gorm.io/gorm/utils/tests"
@@ -31,15 +32,24 @@ func TestUpdateHasOne(t *testing.T) {
3132

3233
var user3 User
3334
DB.Preload("Account").Find(&user3, "id = ?", user.ID)
35+
3436
CheckUser(t, user2, user3)
37+
var lastUpdatedAt = user2.Account.UpdatedAt
38+
time.Sleep(time.Second)
3539

3640
if err := DB.Session(&gorm.Session{FullSaveAssociations: true}).Save(&user).Error; err != nil {
3741
t.Fatalf("errors happened when update: %v", err)
3842
}
3943

4044
var user4 User
4145
DB.Preload("Account").Find(&user4, "id = ?", user.ID)
42-
CheckUser(t, user4, user)
46+
47+
if lastUpdatedAt.Format(time.RFC3339) == user4.Account.UpdatedAt.Format(time.RFC3339) {
48+
t.Fatalf("updated at should be updated, but not, old: %v, new %v", lastUpdatedAt.Format(time.RFC3339), user3.Account.UpdatedAt.Format(time.RFC3339))
49+
} else {
50+
user.Account.UpdatedAt = user4.Account.UpdatedAt
51+
CheckUser(t, user4, user)
52+
}
4353

4454
t.Run("Polymorphic", func(t *testing.T) {
4555
var pet = Pet{Name: "create"}

0 commit comments

Comments
 (0)