package user_m import ( "git.hilo.cn/hilo-common/_const/common" "git.hilo.cn/hilo-common/domain" "git.hilo.cn/hilo-common/resource/mysql" "gorm.io/gorm" "hilo-user/myerr" "time" ) type Relation struct { // 永恒之心值 HeartValue uint32 `json:"heartValue"` // 永恒之心的最大值(0代表没有永恒之心,即没有相互关注) HeartValueMax uint32 `json:"heartValueMax"` // 成长关系建立的时间(天数) MeetDays uint `json:"meetDays"` } //用户成长关系 type UserRelation struct { mysql.Entity *domain.Model `gorm:"-"` UserId_1 mysql.ID UserId_2 mysql.ID HeartValue uint32 } // 查询成长关系 func GetRelation(model *domain.Model, userId1, userId2 mysql.ID) (Relation, error) { result := Relation{0, 0, 0} if userId1 == userId2 { return result, nil } // 保证uid小的在前面 if userId1 > userId2 { userId1, userId2 = userId2, userId1 } rel := UserRelation{UserId_1: userId1, UserId_2: userId2, HeartValue: 0} if err := model.DB().Model(&UserRelation{}).Where(&UserRelation{ UserId_1: userId1, UserId_2: userId2, }).First(&rel).Error; err != nil { if err == gorm.ErrRecordNotFound { // 没有成长关系的情况 return result, nil } else { return result, myerr.WrapErr(err) } } result.HeartValueMax = common.HEART_VALUE_MAX result.HeartValue = rel.HeartValue if result.HeartValue > common.HEART_VALUE_MAX { result.HeartValue = common.HEART_VALUE_MAX } d := uint(time.Since(rel.CreatedTime).Hours() / 24) if d < 0 { d = 0 } result.MeetDays = d return result, nil } // 批量查询成长关系 func BatchGetRelations(model *domain.Model, userId mysql.ID, others []mysql.ID) (map[mysql.ID]Relation, error) { smaller := make([]mysql.ID, 0) greater := make([]mysql.ID, 0) for _, i := range others { if i < userId { smaller = append(smaller, i) } else if i > userId { greater = append(greater, i) } } rows := make([]UserRelation, 0) result := make(map[mysql.ID]Relation, 0) var err error if len(greater) > 0 { if err = model.DB().Model(&UserRelation{}).Where("user_id_1 = ? AND user_id_2 IN ?", userId, greater).Find(&rows).Error; err != nil { return result, err } } for _, i := range rows { if i.HeartValue > common.HEART_VALUE_MAX { i.HeartValue = common.HEART_VALUE_MAX } d := uint(time.Since(i.CreatedTime).Hours() / 24) if d < 0 { d = 0 } result[i.UserId_2] = Relation{HeartValue: i.HeartValue, HeartValueMax: common.HEART_VALUE_MAX, MeetDays: d} } rows = make([]UserRelation, 0) if len(smaller) > 0 { if err = model.DB().Model(&UserRelation{}).Where("user_id_1 IN ? AND user_id_2 = ?", smaller, userId).Find(&rows).Error; err != nil { return result, err } } for _, i := range rows { if i.HeartValue > common.HEART_VALUE_MAX { i.HeartValue = common.HEART_VALUE_MAX } d := uint(time.Since(i.CreatedTime).Hours() / 24) if d < 0 { d = 0 } result[i.UserId_1] = Relation{HeartValue: i.HeartValue, HeartValueMax: common.HEART_VALUE_MAX, MeetDays: d} } // 补上没有成长关系的人 for _, u := range others { if _, exists := result[u]; !exists { result[u] = Relation{0, 0, 0} } } return result, err }