rank.go 1.44 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 44 45 46 47 48 49
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").
		Where("r.date BETWEEN ? AND ?", beginDate, endDate).
		Order("r.score DESC").Offset(offset).Limit(limit).Select("r.*").Find(&ranks).Error; err != nil {
		model.Log.Errorf("PageCpDayRank fail:%v", err)
	}
	return ranks
}