From e331c04e1ee841746ae32ee38a60f4029395c7ac Mon Sep 17 00:00:00 2001 From: a631807682 <631807682@qq.com> Date: Thu, 21 Apr 2022 14:11:33 +0800 Subject: [PATCH] fix: stmt.Changed zero value filed behavior --- statement.go | 9 ++++++--- tests/hooks_test.go | 10 ++++++++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/statement.go b/statement.go index 9fcee09c..880fdb9b 100644 --- a/statement.go +++ b/statement.go @@ -605,10 +605,10 @@ func (stmt *Statement) Changed(fields ...string) bool { changed := func(field *schema.Field) bool { fieldValue, _ := field.ValueOf(stmt.Context, modelValue) if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) { - if v, ok := stmt.Dest.(map[string]interface{}); ok { - if fv, ok := v[field.Name]; ok { + if mapV, mapOk := stmt.Dest.(map[string]interface{}); mapOk { + if fv, ok := mapV[field.Name]; ok { return !utils.AssertEqual(fv, fieldValue) - } else if fv, ok := v[field.DBName]; ok { + } else if fv, ok := mapV[field.DBName]; ok { return !utils.AssertEqual(fv, fieldValue) } } else { @@ -618,6 +618,9 @@ func (stmt *Statement) Changed(fields ...string) bool { } changedValue, zero := field.ValueOf(stmt.Context, destValue) + if v { + return !utils.AssertEqual(changedValue, fieldValue) + } return !zero && !utils.AssertEqual(changedValue, fieldValue) } } diff --git a/tests/hooks_test.go b/tests/hooks_test.go index 0e6ab2fe..20e8dc18 100644 --- a/tests/hooks_test.go +++ b/tests/hooks_test.go @@ -375,13 +375,19 @@ func TestSetColumn(t *testing.T) { t.Errorf("invalid data after update, got %+v", product) } + // Code changed, price should changed + DB.Model(&product).Select("Name", "Code", "Price").Updates(Product3{Name: "Product New4", Code: ""}) + if product.Name != "Product New4" || product.Price != 320 || product.Code != "" { + t.Errorf("invalid data after update, got %+v", product) + } + DB.Model(&product).UpdateColumns(Product3{Code: "L1215"}) - if product.Price != 270 || product.Code != "L1215" { + if product.Price != 320 || product.Code != "L1215" { t.Errorf("invalid data after update, got %+v", product) } DB.Model(&product).Session(&gorm.Session{SkipHooks: true}).Updates(Product3{Code: "L1216"}) - if product.Price != 270 || product.Code != "L1216" { + if product.Price != 320 || product.Code != "L1216" { t.Errorf("invalid data after update, got %+v", product) }