Fix update UpdatedAt when full saving associations, close #4115

This commit is contained in:
Jinzhu 2021-02-26 17:11:25 +08:00
parent 189547f615
commit eb9a704fda
3 changed files with 21 additions and 1 deletions

View File

@ -361,6 +361,7 @@ func saveAssociations(db *gorm.DB, rel *schema.Relationship, values interface{},
}
tx := db.Session(&gorm.Session{NewDB: true}).Clauses(onConflict).Session(&gorm.Session{
FullSaveAssociations: db.FullSaveAssociations,
SkipHooks: db.Statement.SkipHooks,
DisableNestedTransaction: true,
})
@ -370,6 +371,10 @@ func saveAssociations(db *gorm.DB, rel *schema.Relationship, values interface{},
return true
})
if tx.Statement.FullSaveAssociations {
tx = tx.InstanceSet("gorm:update_track_time", true)
}
if len(selects) > 0 {
tx = tx.Select(selects)
} else if len(selectColumns) > 0 && len(omits) == 0 {

View File

@ -320,6 +320,11 @@ func ConvertToCreateValues(stmt *gorm.Statement) (values clause.Values) {
field.Set(stmt.ReflectValue, curTime)
values.Values[0][idx], _ = field.ValueOf(stmt.ReflectValue)
}
} else if field.AutoUpdateTime > 0 {
if _, ok := stmt.DB.InstanceGet("gorm:update_track_time"); ok {
field.Set(stmt.ReflectValue, curTime)
values.Values[0][idx], _ = field.ValueOf(stmt.ReflectValue)
}
}
}

View File

@ -2,6 +2,7 @@ package tests_test
import (
"testing"
"time"
"gorm.io/gorm"
. "gorm.io/gorm/utils/tests"
@ -31,7 +32,10 @@ func TestUpdateHasOne(t *testing.T) {
var user3 User
DB.Preload("Account").Find(&user3, "id = ?", user.ID)
CheckUser(t, user2, user3)
var lastUpdatedAt = user2.Account.UpdatedAt
time.Sleep(time.Second)
if err := DB.Session(&gorm.Session{FullSaveAssociations: true}).Save(&user).Error; err != nil {
t.Fatalf("errors happened when update: %v", err)
@ -39,7 +43,13 @@ func TestUpdateHasOne(t *testing.T) {
var user4 User
DB.Preload("Account").Find(&user4, "id = ?", user.ID)
if lastUpdatedAt.Format(time.RFC3339) == user4.Account.UpdatedAt.Format(time.RFC3339) {
t.Fatalf("updated at should be updated, but not, old: %v, new %v", lastUpdatedAt.Format(time.RFC3339), user3.Account.UpdatedAt.Format(time.RFC3339))
} else {
user.Account.UpdatedAt = user4.Account.UpdatedAt
CheckUser(t, user4, user)
}
t.Run("Polymorphic", func(t *testing.T) {
var pet = Pet{Name: "create"}