fix: update panic if model is not ptr

This commit is contained in:
black 2023-02-07 16:26:41 +08:00
parent e1f46eb802
commit 72decd069b
2 changed files with 33 additions and 0 deletions

View File

@ -17,6 +17,9 @@ func callMethod(db *gorm.DB, fc func(value interface{}, tx *gorm.DB) bool) {
db.Statement.CurDestIndex++ db.Statement.CurDestIndex++
} }
case reflect.Struct: case reflect.Struct:
if !db.Statement.ReflectValue.CanAddr() {
db.Statement.ReflectValue = reflect.New(db.Statement.ReflectValue.Type()).Elem()
}
fc(db.Statement.ReflectValue.Addr().Interface(), tx) fc(db.Statement.ReflectValue.Addr().Interface(), tx)
} }
} }

View File

@ -514,3 +514,33 @@ func TestFailedToSaveAssociationShouldRollback(t *testing.T) {
t.Fatalf("AfterFind should not be called times:%d", productWithItem.Item.AfterFindCallTimes) t.Fatalf("AfterFind should not be called times:%d", productWithItem.Item.AfterFindCallTimes)
} }
} }
type Product5 struct {
gorm.Model
Name string
}
var beforeUpdateCall int
func (p *Product5) BeforeUpdate(*gorm.DB) error {
beforeUpdateCall = beforeUpdateCall + 1
return nil
}
func TestUpdateCallbacks(t *testing.T) {
DB.Migrator().DropTable(&Product5{})
DB.AutoMigrate(&Product5{})
p := Product5{Name: "unique_code"}
DB.Model(&Product5{}).Create(&p)
DB.Model(&Product5{}).Where("id", p.ID).Update("name", "update_name_1")
if beforeUpdateCall != 1 {
t.Fatalf("before update should be called")
}
DB.Model(Product5{}).Where("id", p.ID).Update("name", "update_name_2")
if beforeUpdateCall != 2 {
t.Fatalf("before update should be called")
}
}