diff --git a/callbacks/update.go b/callbacks/update.go index 8b51b2b45..d3a73871f 100644 --- a/callbacks/update.go +++ b/callbacks/update.go @@ -1,6 +1,7 @@ package callbacks import ( + "fmt" "reflect" "sort" @@ -33,13 +34,13 @@ func SetupUpdateReflectValue(db *gorm.DB) { func BeforeUpdate(db *gorm.DB) { if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && (db.Statement.Schema.BeforeSave || db.Statement.Schema.BeforeUpdate) { callMethod(db, func(value interface{}, tx *gorm.DB) (called bool) { - // rv := reflect.ValueOf(value) - // for rv.Kind() == reflect.Ptr { - // rv = rv.Elem() - // } - // // save a copy before executing the hook so that can find out which fields were modified after the hook is executed. - // rvClone := reflect.New(rv.Type()).Elem() - // rvClone.Set(rv) + rv := reflect.ValueOf(value) + for rv.Kind() == reflect.Ptr { + rv = rv.Elem() + } + // save a copy before executing the hook so that can find out which fields were modified after the hook is executed. + rvClone := reflect.New(rv.Type()).Elem() + rvClone.Set(rv) if db.Statement.Schema.BeforeSave { if i, ok := value.(BeforeSaveInterface); ok { @@ -55,18 +56,20 @@ func BeforeUpdate(db *gorm.DB) { } } - // if called { - // fields := db.Statement.Schema.Fields - // for i := 0; i < len(fields); i++ { - // if fields[i].PrimaryKey { - // continue - // } - // // compare with the copy value and update the field if there is a difference - // if !reflect.DeepEqual(rv.FieldByName(fields[i].Name).Interface(), rvClone.FieldByName(fields[i].Name).Interface()) { - // db.Statement.SetColumn(fields[i].DBName, rv.Field(i).Interface()) - // } - // } - // } + if called { + fields := db.Statement.Schema.Fields + for i := 0; i < len(fields); i++ { + if fields[i].PrimaryKey { + continue + } + + // compare with the copy value and update the field if there is a difference + if !reflect.DeepEqual(rv.FieldByName(fields[i].Name).Interface(), rvClone.FieldByName(fields[i].Name).Interface()) { + fmt.Println(rv.FieldByName(fields[i].Name).Interface(), rvClone.FieldByName(fields[i].Name).Interface()) + db.Statement.SetColumn(fields[i].DBName, rv.Field(i).Interface()) + } + } + } return called }) }