package model import ( "context" "fmt" "git.noahlan.cn/northlan/ntools-go/gorm-zero/gormc" "gorm.io/gorm" ) var _ RankPvpModel = (*customRankPvpModel)(nil) const ( RankTypeDamage = iota + 1 RankTypeGeneral RankTypeKillUnit RankTypeKillPlayer ) const MaxRankN = 50 type ( // RankPvpModel is an interface to be customized, add more methods here, // and implement the added methods in customRankPvpModel. RankPvpModel interface { rankPvpModel RankListByType(ctx context.Context, rankType, topN int32) ([]RankPvpWithPlatformUser, error) UpdateRank(ctx context.Context, rankType int32, data []RankPvp) error } customRankPvpModel struct { *defaultRankPvpModel } RankPvpWithPlatformUser struct { RankPvp Platform string // 平台类型 PUname string // 平台用户名 PAvatar string // 平台用户头像地址 } ) // NewRankPvpModel returns a model for the database table. func NewRankPvpModel(conn *gorm.DB) RankPvpModel { return &customRankPvpModel{ defaultRankPvpModel: newRankPvpModel(conn), } } func (m *customRankPvpModel) RankListByType(ctx context.Context, rankType, topN int32) ([]RankPvpWithPlatformUser, error) { db := m.conn.WithContext(ctx) limit := topN if limit > MaxRankN { limit = MaxRankN } var result []RankPvpWithPlatformUser err := db.Model(&RankPvpWithPlatformUser{}). Select(fmt.Sprintf("%s.*, UP.platform, UP.p_uname, UP.p_avatar", m.table)). Joins(fmt.Sprintf("LEFT JOIN user_platform UP ON UP.user_id = %s.user_id", m.table)). Where("rank_type = ?", rankType). Limit(int(limit)). Order("score desc"). // score 排名 Find(&result).Error switch err { case nil: return result, nil case gormc.ErrNotFound: return nil, ErrNotFound default: return nil, err } } func (m *customRankPvpModel) UpdateRank(ctx context.Context, rankType int32, data []RankPvp) error { db := m.conn.WithContext(ctx) //.Session(&gorm.Session{DryRun: true}) return db.Transaction(func(tx *gorm.DB) error { var err error // delete all by rank_type if err = tx. Table(m.table). Where("rank_type = ?", rankType). Delete(&RankPvp{}).Error; err != nil { return err } // add all if err = tx. Create(data).Error; err != nil { return err } return nil }) }