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
90
91
92
93
94
95
96
|
// model/object.go
type Object struct {
ID uint `db:"id" json:"id"`
Title string `db:"title" json:"title"`
}
type OKR struct {
Object
KR []*KR `json:"kr"`
}
// model/key_result.go
type KR struct {
ID uint `db:"id" json:"id"`
ObjectId uint `db:"object_id" json:"object_id"`
Title string `db:"title" json:"title"`
}
// dao/object.go
type Object struct{}
func NewObject() *Object {
return &Object{}
}
func (d *Object) GetObjs() (okrs []*model.OKR, err error) {
err = db.Select(&okrs, "select id,title from objects order by id DESC limit 10 offset 0")
return
}
// dao/key_result.go
type KeyResult struct{}
func NewKeyResult() *KeyResult {
return &KeyResult{}
}
func (d *KeyResult) GetKrs(oids []uint) (krs []*model.KR, err error) {
query, agrs, err := sqlx.In("select id,object_id,title from key_results where object_id in (?)", oids)
if err != nil {
return
}
query = db.Rebind(query)
db.Select(&krs, query, agrs...)
return
}
// service/okr.go
type OKRs struct {
dObj *dao.Object
dKR *dao.KeyResult
}
func NewOKR() *OKRs {
return &OKRs{
dObj: dao.NewObject(),
dKR: dao.NewKeyResult(),
}
}
func (s *OKR) List() (okrs []*model.OKR, err error) {
okrs, err = s.dObj.GetObjs()
if err != nil {
return
}
krs, err := s.dKR.GetKrs(s.GetObjIDs(okrs))
if err != nil {
return
}
for i, o := range okrs {
okrs[i].KR = s.GetKrByID(krs, o.ID)
}
return
}
func (s *OKR) GetObjIDs(okrs []*model.OKR) (ids []uint) {
krs := make(map[uint]struct{}, 0) // 防止重复的ID
for _, v := range okrs {
if _, ok := krs[v.ID]; ok {
continue
}
krs[v.ID] = struct{}{}
ids = append(ids, v.ID)
}
return
}
func (s *OKR) GetKrByID(krs []*model.KR, oid uint) (fkr []*model.KR) {
for _, kr := range krs {
if kr.ObjectId != oid {
continue
}
fkr = append(fkr, kr)
}
return
}
|