feat(repository): enhance repository methods with batch processing and transaction support
All checks were successful
Build Backend / build (push) Successful in 12m50s
Build Backend / build-docker (push) Successful in 2m57s

- Updated Like and Unlike methods in CommentRepository to use transactions for data consistency.
- Introduced IsLikedBatch method for batch checking if comments are liked, addressing N+1 query issues.
- Enhanced BatchDelete method in PostRepository to perform batch deletions within a single transaction, improving efficiency.
- Added BatchUpdateStatus method for posts to utilize a single SQL update for status changes, reducing database load.
- Implemented BatchUpdateSortOrder in StickerRepository using CASE WHEN for efficient sorting updates.
- Added IsFollowingBatch and IsBlockedBatch methods in UserRepository for batch checking follow and block relationships, optimizing performance.
This commit is contained in:
lafay
2026-03-26 01:50:54 +08:00
parent 56bd971e42
commit 7b41dfeb00
9 changed files with 386 additions and 109 deletions

View File

@@ -4,6 +4,7 @@ import (
"carrot_bbs/internal/model"
"carrot_bbs/internal/pkg/cursor"
"context"
"errors"
"gorm.io/gorm"
)
@@ -188,6 +189,36 @@ func (r *groupRepository) IsMember(groupID string, userID string) (bool, error)
return count > 0, err
}
// GetExistingMembers 批量检查用户是否是群成员(解决 N+1 问题)
// 返回 map[userID]bool
func (r *groupRepository) GetExistingMembers(groupID string, userIDs []string) (map[string]bool, error) {
result := make(map[string]bool)
if len(userIDs) == 0 || groupID == "" {
return result, nil
}
// 初始化所有用户为 false
for _, id := range userIDs {
result[id] = false
}
// 一次性查询所有群成员记录
var existingIDs []string
err := r.db.Model(&model.GroupMember{}).
Where("group_id = ? AND user_id IN ?", groupID, userIDs).
Pluck("user_id", &existingIDs).Error
if err != nil {
return nil, err
}
// 更新已存在的成员
for _, id := range existingIDs {
result[id] = true
}
return result, nil
}
// GetUserGroups 获取用户加入的群组列表
func (r *groupRepository) GetUserGroups(userID string, page, pageSize int) ([]model.Group, int64, error) {
var groups []model.Group
@@ -318,7 +349,7 @@ func (r *groupRepository) GetLatestAnnouncement(groupID string) (*model.GroupAnn
Order("is_pinned DESC, created_at DESC").
First(&announcement).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err