| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- package model
- import (
- "context"
- "gorm.io/gorm"
- )
- type UserFollow struct {
- *Model
- UserId int64 `gorm:"column:user_id;default:0;NOT NULL"` // 用户id
- ToUserId int64 `gorm:"column:to_user_id;default:0;NOT NULL"` // 被关注的用户id
- }
- func (m *UserFollow) TableName() string {
- return "p_user_follow"
- }
- type UserFollowModel struct {
- conn *gorm.DB
- }
- func NewUserFollowModel(conn *gorm.DB) UserFollowModel {
- return UserFollowModel{
- conn: conn,
- }
- }
- // GetFansList 获取用户的粉丝列表
- func (m *UserFollowModel) GetFansList(ctx context.Context, userId int64, page, pageSize int) ([]*UserFollow, error) {
- var follows []*UserFollow
- offset := (page - 1) * pageSize
- err := m.conn.WithContext(ctx).
- Where("to_user_id = ? AND is_del = 0", userId).
- Offset(offset).
- Limit(pageSize).
- Order("created_on desc").
- Find(&follows).Error
- if err != nil {
- return nil, err
- }
- return follows, nil
- }
- // GetFollowsList 获取用户的关注列表
- func (m *UserFollowModel) GetFollowsList(ctx context.Context, userId int64, page, pageSize int) ([]*UserFollow, error) {
- var follows []*UserFollow
- offset := (page - 1) * pageSize
- err := m.conn.WithContext(ctx).
- Where("user_id = ? AND is_del = 0", userId).
- Offset(offset).
- Limit(pageSize).
- Order("created_on desc").
- Find(&follows).Error
- if err != nil {
- return nil, err
- }
- return follows, nil
- }
- // CheckMutualFollows 批量检查用户之间的关注关系
- func (m *UserFollowModel) CheckMutualFollows(ctx context.Context, userId int64, targetUserIds []int64) (map[int64]bool, error) {
- var follows []*UserFollow
- result := make(map[int64]bool)
- // 初始化结果map
- for _, targetId := range targetUserIds {
- result[targetId] = false
- }
- // 查询当前用户是否关注了目标用户们
- err := m.conn.WithContext(ctx).
- Where("user_id = ? AND to_user_id IN ? AND is_del = 0", userId, targetUserIds).
- Find(&follows).Error
- if err != nil {
- return nil, err
- }
- // 标记已关注的用户
- for _, follow := range follows {
- result[follow.ToUserId] = true
- }
- return result, nil
- }
- // UnFollow 取消关注
- func (m *UserFollowModel) UnFollow(ctx context.Context, userId, toUserId int64) error {
- return m.conn.WithContext(ctx).
- Model(&UserFollow{}).
- Where("user_id = ? AND to_user_id = ? AND is_del = 0", userId, toUserId).
- Update("is_del", 1).Error
- }
- // Follow 关注用户
- func (m *UserFollowModel) Follow(ctx context.Context, userId, toUserId int64) error {
- return m.conn.WithContext(ctx).Create(&UserFollow{
- UserId: userId,
- ToUserId: toUserId,
- }).Error
- }
|