rank.go 1.9 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
package cp_m

import (
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/resource/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"time"
)

type CpDayRank struct {
	Date        string
	CpId        mysql.ID
	UserId1     mysql.ID
	UserId2     mysql.ID
	Score       mysql.Num
	CreatedTime time.Time `gorm:"->"`
	UpdatedTime time.Time `gorm:"->"`
}

// 增加cp排行榜-天
func AddCpDayRank(model *domain.Model, cpRelation CpRelationTmp, score mysql.Num) (err error) {
	date := time.Now().Format("2006-01-02")
	rank := &CpDayRank{
		Date:    date,
		CpId:    cpRelation.ID,
		UserId1: cpRelation.UserId1,
		UserId2: cpRelation.UserId2,
		Score:   score,
	}
	if err = model.DB().Model(CpDayRank{}).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "date"}, {Name: "cp_id"}},
		DoUpdates: clause.Assignments(map[string]interface{}{
			"score": gorm.Expr("score + ?", rank.Score)})}).Create(rank).Error; err != nil {
		model.Log.Errorf("AddCpDayRank fail:%v", err)
		return err
	}
	return nil
}

// 分页获取cp排行榜
func PageCpDayRank(model *domain.Model, beginDate, endDate string, offset, limit int) []CpDayRank {
	var ranks []CpDayRank
	if err := model.DB().Table("cp_day_rank r").Joins("INNER JOIN cp_relation c ON c.id = r.cp_id").
hujiebin's avatar
hujiebin committed
44
		Where("r.date BETWEEN ? AND ?", beginDate, endDate).Group("cp_id").Select("cp_id,r.user_id1,r.user_id2,SUM(r.score) score").
hujiebin's avatar
hujiebin committed
45
		Order("score DESC").Offset(offset).Limit(limit).Find(&ranks).Error; err != nil {
hujiebin's avatar
hujiebin committed
46 47 48 49
		model.Log.Errorf("PageCpDayRank fail:%v", err)
	}
	return ranks
}
hujiebin's avatar
hujiebin committed
50 51 52 53 54

// 获取指定cp排行榜
func GetCpDayRank(model *domain.Model, beginDate, endDate string, cpId mysql.ID) CpDayRank {
	var rank CpDayRank
	if err := model.DB().Table("cp_day_rank").
hujiebin's avatar
hujiebin committed
55 56
		Where("date BETWEEN ? AND ?", beginDate, endDate).Where("cp_id = ?", cpId).Select("cp_id,user_id1,user_id2,SUM(score) score").
		First(&rank).Error; err != nil {
hujiebin's avatar
hujiebin committed
57 58 59 60
		model.Log.Errorf("GetCpDayRank fail:%v", err)
	}
	return rank
}