-
Notifications
You must be signed in to change notification settings - Fork 73
/
gorm2.go
64 lines (54 loc) · 1.57 KB
/
gorm2.go
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package gorm2
import (
"time"
"github.com/jinzhu/gorm"
)
func getGormDB() *gorm.DB {
db, _ := gorm.Open("mysql",
"user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
return db
}
// User struct represents user model.
type User struct {
gorm.Model
Rating int
RatingMarks int
}
func getTodayBegin() time.Time {
year, month, day := time.Now().Date()
return time.Date(year, month, day, 0, 0, 0, 0, time.Now().Location())
}
func queryUsersWithMaxRating(db *gorm.DB, limit int) *gorm.DB {
return db.Order("rating DESC").Limit(limit)
}
func queryUsersRegisteredToday(db *gorm.DB, limit int) *gorm.DB {
today := getTodayBegin()
return db.Where("created_at >= ?", today).Limit(limit)
}
// GetUsersWithMaxRating returns limit users with maximal rating
func GetUsersWithMaxRating(limit int) ([]User, error) {
var users []User
if err := queryUsersWithMaxRating(getGormDB(), limit).Find(&users).Error; err != nil {
return nil, err
}
return users, nil
}
// GetUsersRegisteredToday returns all users registered today
func GetUsersRegisteredToday(limit int) ([]User, error) {
var users []User
if err := queryUsersRegisteredToday(getGormDB(), limit).Find(&users).Error; err != nil {
return nil, err
}
return users, nil
}
// GetUsersRegisteredTodayWithMaxRating returns all users
// registered today with max rating
func GetUsersRegisteredTodayWithMaxRating(limit int) ([]User, error) {
var users []User
err := queryUsersWithMaxRating(queryUsersRegisteredToday(getGormDB(), limit), limit).
Find(&users).Error
if err != nil {
return nil, err
}
return users, nil
}