package noble_m import ( "gorm.io/gorm" "hilo-user/resource/mysql" "time" ) type UserNoble struct { mysql.Entity UserId uint64 Level uint16 EndTime time.Time } func (ub *UserNoble) Create(db *gorm.DB) error { return db.Create(ub).Error } func (ub *UserNoble) UpdateEndTime(db *gorm.DB, endTime time.Time) (int64, error) { r := db.Model(&UserNoble{}).Where(ub).Update("end_time", endTime) return r.RowsAffected, r.Error } // 查询用户未过期的贵族 func (ub *UserNoble) Find(db *gorm.DB) ([]UserNoble, error) { rows := make([]UserNoble, 0) if err := db.Where(ub).Where("end_time>=NOW()").Order("level DESC").Find(&rows).Error; err != nil { return nil, err } return rows, nil } // 查询用户所有的贵族(包括已过期) func (ub *UserNoble) FindAll(db *gorm.DB) ([]UserNoble, error) { rows := make([]UserNoble, 0) if err := db.Where(ub).Order("level DESC").Find(&rows).Error; err != nil { return nil, err } return rows, nil } func RemoveNoble(db *gorm.DB, userId uint64, level uint16) error { ub := UserNoble{ UserId: userId, Level: level, } return ub.Delete(db) } func (ub *UserNoble) Delete(db *gorm.DB) error { return db.Where(ub).Delete(&UserNoble{}).Error } // 查询用户未过期的贵族 func (ub *UserNoble) batchGet(db *gorm.DB, userIds []uint64) (map[uint64][]UserNoble, error) { rows := make([]UserNoble, 0) if err := db.Model(ub).Where("end_time>=NOW() AND user_id IN ?", userIds).Order("level DESC").Find(&rows).Error; err != nil { return nil, err } result := make(map[uint64][]UserNoble, 0) for _, i := range rows { if _, ok := result[i.UserId]; !ok { result[i.UserId] = make([]UserNoble, 0) } result[i.UserId] = append(result[i.UserId], i) } return result, nil } func FindActiveNoble(db *gorm.DB, userId uint64) (*UserNoble, error) { ub := UserNoble{ UserId: userId, } records, err := ub.Find(db) if err != nil { return nil, err } if len(records) <= 0 { return nil, nil } return &records[0], nil } func GetNobleLevel(db *gorm.DB, userId uint64) (uint16, error) { noble, err := FindActiveNoble(db, userId) if err != nil { return 0, err } if noble == nil { return 0, nil } else { return noble.Level, nil } }