添加callback,迁移文件
This commit is contained in:
@@ -87,6 +87,12 @@ func InitPostgreSQL(cfg *config.DatabaseConfig, log *zap.Logger) (*gorm.DB, erro
|
||||
zap.Int("max_idle_conns", maxIdleConns),
|
||||
zap.Duration("conn_max_lifetime", connMaxLifetime))
|
||||
|
||||
// db.AutoMigrate(
|
||||
// &model.Account{},
|
||||
// &model.Role{},
|
||||
// &model.Permission{},
|
||||
// &model.RolePermission{},
|
||||
// )
|
||||
return db, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package gorm
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/logger"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"go.uber.org/zap"
|
||||
@@ -42,8 +43,8 @@ type AccountStoreInterface interface {
|
||||
// 4. 通过 SkipDataPermission(ctx) 可以绕过权限过滤
|
||||
//
|
||||
// 注意:
|
||||
// - Callback 只对包含 creator 字段的表生效
|
||||
// - 必须在初始化 Store 之前注册
|
||||
// - Callback 只对包含 creator 字段的表生效
|
||||
// - 必须在初始化 Store 之前注册
|
||||
//
|
||||
// 参数:
|
||||
// - db: GORM DB 实例
|
||||
@@ -110,7 +111,24 @@ func RegisterDataPermissionCallback(db *gorm.DB, accountStore AccountStoreInterf
|
||||
tx.Where("creator IN ?", subordinateIDs)
|
||||
}
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// RegisterSetCreatorUpdaterCallback 注册 GORM 创建数据时创建人更新人 Callback
|
||||
func RegisterSetCreatorUpdaterCallback(db *gorm.DB) error {
|
||||
err := db.Callback().Create().Before("gorm:create").Register("set_creator_updater", func(tx *gorm.DB) {
|
||||
ctx := tx.Statement.Context
|
||||
if userID, ok := tx.Statement.Context.Value(constants.ContextKeyUserID).(uint); ok {
|
||||
if f := tx.Statement.Schema; f != nil {
|
||||
if c, ok := f.FieldsByName["Creator"]; ok {
|
||||
_ = c.Set(ctx, tx.Statement.ReflectValue, userID)
|
||||
}
|
||||
if u, ok := f.FieldsByName["Updater"]; ok {
|
||||
_ = u.Set(ctx, tx.Statement.ReflectValue, userID)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user