forked from jirfag/go-queryset
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorm3.go
71 lines (61 loc) · 1.54 KB
/
gorm3.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
65
66
67
68
69
70
71
package gorm3
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) *gorm.DB {
return db.Order("rating DESC")
}
func queryUsersRegisteredToday(db *gorm.DB) *gorm.DB {
return db.Where("created_at >= ?", getTodayBegin())
}
// GetUsersWithMaxRating returns limit users with maximal rating
func GetUsersWithMaxRating(limit int) ([]User, error) {
var users []User
err := queryUsersWithMaxRating(getGormDB()).
Limit(limit).
Find(&users).Error
if err != nil {
return nil, err
}
return users, nil
}
// GetUsersRegisteredToday returns all users registered today
func GetUsersRegisteredToday(limit int) ([]User, error) {
var users []User
err := queryUsersRegisteredToday(getGormDB()).
Limit(limit).
Find(&users).Error
if 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 := getGormDB().
Scopes(queryUsersWithMaxRating, queryUsersRegisteredToday).
Limit(limit).
Find(&users).Error
if err != nil {
return nil, err
}
return users, nil
}