achievement.go 1.75 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
package cp_m

import (
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/resource/mysql"
	"gorm.io/gorm"
	"hilo-user/_const/enum/cp_e"
	"time"
)

type CpAchievement struct {
	CpId        mysql.ID
	UserId1     mysql.ID
	UserId2     mysql.ID
	Type        cp_e.CpAchievement
	Score       mysql.Num
	CreatedTime time.Time `gorm:"->"`
	UpdatedTime time.Time `gorm:"->"`
}

// 更新cp成就
// 单进程操作,先create,后update
func UpdateCpAchievement(model *domain.Model, cpId, userId1, userId2 mysql.ID, Type cp_e.CpAchievement, score mysql.Num) error {
	var cpAchievement CpAchievement
	if err := model.DB().Model(CpAchievement{}).Where("cp_id = ? AND `type` = ?", cpId, Type).First(&cpAchievement).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			model.Log.Errorf("UpdateCpAchievement fail:%v", err)
			return err
		}
		// gorm.ErrRecordNotFound
		cpAchievement = CpAchievement{
			CpId:    cpId,
			UserId1: userId1,
			UserId2: userId2,
			Type:    Type,
			Score:   score,
		}
		return model.DB().Model(CpAchievement{}).Create(&cpAchievement).Error
	}
	// update if less than
	return model.DB().Model(CpAchievement{}).Where("cp_id = ? AND `type` = ?", cpId, Type).Where("score < ?", score).UpdateColumn("score", score).Error
}
hujiebin's avatar
hujiebin committed
43

hujiebin's avatar
hujiebin committed
44 45
// 获取cp成就
func GetCpAchievements(model *domain.Model) []CpAchievement {
hujiebin's avatar
hujiebin committed
46
	var achievements []CpAchievement
hujiebin's avatar
hujiebin committed
47
	subQuery := model.DB().Table("cp_achievement a").Joins("JOIN cp_relation r ON a.cp_id = r.id").Select("type,MAX(score) AS max_score").Group("type")
hujiebin's avatar
hujiebin committed
48
	if err := model.DB().Model(CpAchievement{}).Joins("INNER JOIN cp_relation r ON cp_id = r.id").Where("(type, score) IN (?)", subQuery).Order("type ASC").Find(&achievements).Error; err != nil {
hujiebin's avatar
hujiebin committed
49 50 51 52
		model.Log.Errorf("GetAchievements fail:%v", err)
	}
	return achievements
}