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 } // 获取cp成就 func GetCpAchievements(model *domain.Model) []CpAchievement { var achievements []CpAchievement 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") if err := model.DB().Model(CpAchievement{}).Where("(type, score) IN (?)", subQuery).Find(&achievements).Error; err != nil { model.Log.Errorf("GetAchievements fail:%v", err) } return achievements }