fix: wrap AssignRoles in transaction and eliminate N+1 queries

- AssignRoles: wrap DeleteByUserID + BatchCreate in DB transaction (P1)
- GetUserRoles: use GetByIDs batch query instead of per-role GetByID loop (N+1 fix)
- ListAdmins: use GetByIDs batch query instead of per-user GetByID loop (N+1 fix)
- Add WithTx/DB methods to UserRoleRepository for transaction support
- Add GetByIDs to UserRepository (batch user lookup)
- Add .gitattributes to normalize line endings to LF (P2)
This commit is contained in:
2026-04-11 10:32:33 +08:00
parent 8c1cf54213
commit c2096ff008
4 changed files with 77 additions and 24 deletions

View File

@@ -18,6 +18,16 @@ func NewUserRoleRepository(db *gorm.DB) *UserRoleRepository {
return &UserRoleRepository{db: db}
}
// DB returns the underlying GORM DB for transaction support
func (r *UserRoleRepository) DB() *gorm.DB {
return r.db
}
// WithTx returns a new repository instance that uses the given transaction
func (r *UserRoleRepository) WithTx(tx *gorm.DB) *UserRoleRepository {
return &UserRoleRepository{db: tx}
}
// Create 创建用户角色关联
func (r *UserRoleRepository) Create(ctx context.Context, userRole *domain.UserRole) error {
return r.db.WithContext(ctx).Create(userRole).Error