-
Notifications
You must be signed in to change notification settings - Fork 0
/
team.go
89 lines (75 loc) · 2.48 KB
/
team.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package models
import (
"math"
"time"
"gorm.io/gorm"
)
// Team represents a team's fields
type Team struct {
gorm.Model
ID uint `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
Name string `gorm:"column:name" json:"name"`
LeaderId uint `gorm:"column:leader_id" json:"leader_id"` // not a foreign key to avoid cycling mess :)
Leader *Contestant `gorm:"-" json:"leader"` // using a pointer to avoid cycling :)
JoinID string `gorm:"column:join_id;unique" json:"join_id"`
Contests []Contest `gorm:"many2many:register_teams;"` // a team may register in more than one contest
Members []Contestant `gorm:"-" json:"members"` // each contestant has their team id :)
}
func (t *Team) AfterFind(db *gorm.DB) error {
if t.ID <= 1 {
return nil
}
err := db.
Model(new(Contestant)).
Find(&t.Leader, "user_id = ?", t.LeaderId).
Error
if err != nil {
return err
}
return db.
Model(new(Contestant)).
Find(&t.Members, "team_id = ?", t.ID).
Error
}
func (t *Team) BeforeDelete(db *gorm.DB) error {
return db.
Model(new(Contestant)).
Where("team_id = ?", t.ID).
Update("team_id", 0).
Error
}
func (t *Team) AfterCreate(db *gorm.DB) error {
for i := range t.Members {
t.Members[i].TeamID = t.ID
t.Members[i].TeamlessContestID = math.MaxInt
t.Members[i].TeamlessedAt = time.Now()
err := db.
Model(&t.Members[i]).
Where("user_id = ?", t.Members[i].User.ID).
Updates(&t.Members[i]).
Error
if err != nil {
return err
}
}
return nil
}
type JoinRequest struct {
gorm.Model
ID uint `gorm:"column:id;primaryKey;autoIncrement"`
RequesterID uint `gorm:"column:requester_id" json:"requester_id"`
RequestedTeamJoinID string `gorm:"column:requested_team_join_id" json:"requested_team_join_id"`
RequestedTeamID uint `gorm:"column:requested_team_id" json:"requested_team_id"`
RequestedTeam Team `gorm:"foreignkey:RequestedTeamID" json:"requested_team"`
RequestedContestID uint `gorm:"column:req_contest_id" json:"requested_contest_id"`
RequestMessage string `gorm:"column:message" json:"request_message"`
NotificationID uint `gorm:"column:notification_id"`
Notification Notification `gorm:"foreignkey:NotificationID"`
}
func (j *JoinRequest) BeforeDelete(db *gorm.DB) error {
return db.
Model(new(Notification)).
Where("id = ?", j.NotificationID).
Delete(&j.Notification).
Error
}