From dacbaa5f02bf40efa5d8841047c047f7a5340d9f Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 27 Aug 2020 19:52:01 +0800 Subject: [PATCH] Fix update attrs order --- callbacks/update.go | 6 ++++-- tests/scanner_valuer_test.go | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/callbacks/update.go b/callbacks/update.go index 73c062b4..46f59157 100644 --- a/callbacks/update.go +++ b/callbacks/update.go @@ -199,7 +199,8 @@ func ConvertToAssignments(stmt *gorm.Statement) (set clause.Set) { } if !stmt.UpdatingColumn && stmt.Schema != nil { - for _, field := range stmt.Schema.FieldsByDBName { + for _, dbName := range stmt.Schema.DBNames { + field := stmt.Schema.LookUpField(dbName) if field.AutoUpdateTime > 0 && value[field.Name] == nil && value[field.DBName] == nil { if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) { now := stmt.DB.NowFunc() @@ -222,7 +223,8 @@ func ConvertToAssignments(stmt *gorm.Statement) (set clause.Set) { switch updatingValue.Kind() { case reflect.Struct: set = make([]clause.Assignment, 0, len(stmt.Schema.FieldsByDBName)) - for _, field := range stmt.Schema.FieldsByDBName { + for _, dbName := range stmt.Schema.DBNames { + field := stmt.Schema.LookUpField(dbName) if !field.PrimaryKey || (!updatingValue.CanAddr() || stmt.Dest != stmt.Model) { if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) { value, isZero := field.ValueOf(updatingValue) diff --git a/tests/scanner_valuer_test.go b/tests/scanner_valuer_test.go index f42daae7..fb1f5791 100644 --- a/tests/scanner_valuer_test.go +++ b/tests/scanner_valuer_test.go @@ -384,7 +384,7 @@ func TestGORMValuer(t *testing.T) { }).Statement if !regexp.MustCompile(`UPDATE .user_with_points. SET .name.=.+,.point.=ST_PointFromText\(.+\)`).MatchString(stmt.SQL.String()) { - t.Errorf("insert with sql.Expr, but got %v", stmt.SQL.String()) + t.Errorf("update with sql.Expr, but got %v", stmt.SQL.String()) } if !reflect.DeepEqual([]interface{}{"jinzhu", "POINT(100 100)"}, stmt.Vars) {