package gormClient
import (
"log"
"os"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func Init(dataSource string) *gorm.DB {
db, err := gorm.Open(mysql.Open(dataSource), &gorm.Config{
Logger: logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags),
logger.Config{
LogLevel: logger.Info,
},
),
})
if err != nil {
return nil
}
db.Callback().Update().Before("gorm:update").Register("update_plagin:before_update", beforeUpdate)
db.Callback().Create().Before("gorm:create").Register("update_plagin:create_update", beforeCreate)
return db
}
func beforeUpdate(db *gorm.DB) {
db.Statement.SetColumn("update_time", time.Now().Format("2006-01-02 15:04:05"))
}
func beforeCreate(db *gorm.DB) {
db.Statement.SetColumn("create_time", time.Now().Format("2006-01-02 15:04:05"))
}
需要注意的是。需要更新的字段必须是定义的,和数据库保持一致的才可以