[ADD]添加callback回调

This commit is contained in:
viletyy 2020-09-26 10:03:30 +08:00
parent eeb859beff
commit 6e1d32a77e
2 changed files with 65 additions and 24 deletions

View File

@ -1,19 +1,12 @@
package models package models
import (
"github.com/jinzhu/gorm"
"time"
)
type Employee struct { type Employee struct {
ID int `gorm:"primary_key" json:"id"` Model
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Password string `json:"password"`
Department string `json:"department"` Department string `json:"department"`
Position string `json:"position"` Position string `json:"position"`
State int `json:"state"` State int `json:"state"`
CreatedOn int `json:"created_on"`
ModifiedOn int `json:"modified_on"`
} }
func CheckEmployee(username, password string) bool { func CheckEmployee(username, password string) bool {
@ -76,16 +69,4 @@ func AddArticle(data map[string]interface{}) bool {
Position: data["position"].(string), Position: data["position"].(string),
}) })
return true return true
} }
func (employee *Employee) BeforeCreate(scope *gorm.Scope) error {
scope.SetColumn("CreateOn", time.Now().Unix())
return nil
}
func (employee *Employee) BeforeUpdate(scope *gorm.Scope) error {
scope.SetColumn("ModifiedOn", time.Now().Unix())
return nil
}

View File

@ -6,6 +6,7 @@ import (
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres" _ "github.com/jinzhu/gorm/dialects/postgres"
"log" "log"
"time"
) )
var db *gorm.DB var db *gorm.DB
@ -14,11 +15,12 @@ type Model struct {
ID int `gorm:"primary_key" json:"id"` ID int `gorm:"primary_key" json:"id"`
CreatedOn int `json:"created_on"` CreatedOn int `json:"created_on"`
ModifiedOn int `json:"modified_on"` ModifiedOn int `json:"modified_on"`
DeleteOn int `json:"deleted_on"`
} }
func init() { func init() {
var ( var (
err error err error
dbType, dbName, user, password, host, port, tablePrefix string dbType, dbName, user, password, host, port, tablePrefix string
) )
@ -55,8 +57,66 @@ func init() {
db.LogMode(true) db.LogMode(true)
db.DB().SetMaxIdleConns(10) db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100) db.DB().SetMaxOpenConns(100)
// 注册Callbacks
db.Callback().Create().Replace("gorm:update_time_stamp", updateTimeStampForCreateCallback)
db.Callback().Update().Replace("gorm:update_time_stamp", updateTimeStampForUpdateCallBack)
db.Callback().Delete().Replace("gorm:delete", deleteCallback)
} }
func CloseDB() { func CloseDB() {
defer db.Close() defer db.Close()
}
func updateTimeStampForCreateCallback(scope *gorm.Scope) {
if !scope.HasError() {
nowTime := time.Now().Unix()
if createTimeField, ok := scope.FieldByName("CreatedOn"); ok {
if createTimeField.IsBlank {
createTimeField.Set(nowTime)
}
}
if modifyTimeField, ok := scope.FieldByName("ModifiedOn"); ok {
if modifyTimeField.IsBlank {
modifyTimeField.Set(nowTime)
}
}
}
}
func updateTimeStampForUpdateCallBack(scope *gorm.Scope) {
if _, ok := scope.Get("gorm:update_column"); !ok {
scope.SetColumn("ModifiedOn", time.Now().Unix())
}
}
func deleteCallback(scope *gorm.Scope) {
if !scope.HasError() {
var extraOption string
if str, ok := scope.Get("gorm:delete_option"); ok {
extraOption = fmt.Sprint(str)
}
deleteOnField, hasDeleteOnField := scope.FieldByName("DeleteOn")
if !scope.Search.Unscoped && hasDeleteOnField {
scope.Raw(fmt.Sprintf(
"update %v SET %v=%v%v%v",
scope.QuotedTableName(),
scope.Quote(deleteOnField.DBName),
scope.AddToVars(time.Now().Unix()),
addExtraSpaceIfExist(scope.CombinedConditionSql()),
addExtraSpaceIfExist(extraOption),
)).Exec()
}
}
}
func addExtraSpaceIfExist(str string) string {
if str != "" {
return " " + str
}
return ""
} }