Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
demoManito committed Aug 21, 2024
1 parent 4c91358 commit ebafebb
Showing 1 changed file with 22 additions and 19 deletions.
41 changes: 22 additions & 19 deletions callbacks/update.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package callbacks

import (
"fmt"
"reflect"
"sort"

Expand Down Expand Up @@ -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 {
Expand All @@ -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
})
}
Expand Down

0 comments on commit ebafebb

Please sign in to comment.