添加callback,迁移文件

This commit is contained in:
2025-12-15 14:37:34 +08:00
parent ad946af5ee
commit 478e37903b
16 changed files with 52 additions and 367 deletions

View File

@@ -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
}