funccropImage(db *gorm.DB) { if db.Statement.Schema != nil { // crop image fields and upload them to CDN, dummy code for _, field := range db.Statement.Schema.Fields { switch db.Statement.ReflectValue.Kind() { case reflect.Slice, reflect.Array: for i := 0; i < db.Statement.ReflectValue.Len(); i++ { // Get value from field if fieldValue, isZero := field.ValueOf(db.Statement.Context, db.Statement.ReflectValue.Index(i)); !isZero { if crop, ok := fieldValue.(CropInterface); ok { crop.Crop() } } } case reflect.Struct: // Get value from field if fieldValue, isZero := field.ValueOf(db.Statement.Context, db.Statement.ReflectValue); !isZero { if crop, ok := fieldValue.(CropInterface); ok { crop.Crop() } }
// Set value to field err := field.Set(db.Statement.Context, db.Statement.ReflectValue, "newValue") } }
// All fields for current model db.Statement.Schema.Fields
// All primary key fields for current model db.Statement.Schema.PrimaryFields
// Prioritized primary key field: field with DB name `id` or the first defined primary key db.Statement.Schema.PrioritizedPrimaryField
// All relationships for current model db.Statement.Schema.Relationships
// Find field with field name or db name field := db.Statement.Schema.LookUpField("Name")
// processing } }
// Register the callback for the Create operation db.Callback().Create().Register("crop_image", cropImage)
删除回调
如果不再需要回调,可以将其删除
// Remove the 'gorm:create' callback from Create operations db.Callback().Create().Remove("gorm:create")
替换回调
可以使用新函数替换同名的回调
// Replace the 'gorm:create' callback with a new function db.Callback().Create().Replace("gorm:create", newCreateFunction)
回调排序
可以注册具有特定顺序的回调,以确保它们在操作生命周期的正确时间执行。
// Register to execute before the 'gorm:create' callback db.Callback().Create().Before("gorm:create").Register("update_created_at", updateCreated)
// Register to execute after the 'gorm:create' callback db.Callback().Create().After("gorm:create").Register("update_created_at", updateCreated)
// Register to execute after the 'gorm:query' callback db.Callback().Query().After("gorm:query").Register("my_plugin:after_query", afterQuery)
// Register to execute after the 'gorm:delete' callback db.Callback().Delete().After("gorm:delete").Register("my_plugin:after_delete", afterDelete)
// Register to execute before the 'gorm:update' callback db.Callback().Update().Before("gorm:update").Register("my_plugin:before_update", beforeUpdate)
// Register to execute before 'gorm:create' and after 'gorm:before_create' db.Callback().Create().Before("gorm:create").After("gorm:before_create").Register("my_plugin:before_create", beforeCreate)
// Register to execute before any other callbacks db.Callback().Create().Before("*").Register("update_created_at", updateCreated)
// Register to execute after any other callbacks db.Callback().Create().After("*").Register("update_created_at", updateCreated)