user_dao.go
2.5 KB
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
package dao
import pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
type UserDao struct {
transactionContext *pgTransaction.TransactionContext
}
func NewUserDao(options map[string]interface{}) *UserDao {
var transactionContext *pgTransaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pgTransaction.TransactionContext)
}
return &UserDao{
transactionContext: transactionContext,
}
}
type UserData1 struct {
Id int `pg:"id"`
ParentId int `pg:"parent_id"`
Account string `pg:"account"` // 用户账号
Name string `pg:"name"` // 用户姓名
Level int `pg:"level"`
}
func (d *UserDao) AllChildUser(userId int) ([]UserData1, error) {
sqlStr := `with
-- 人员自身以及全下级
recursive t_user as (
(
select "user".id,"user".parent_id ,"user".account,"user".name, 1 as "level"
from "user"
where "user".id=? and "user".deleted_at isnull
)
union
(
select "child_user".id,"child_user".parent_id,"child_user".account,"child_user".name,
"parent_user"."level"+1 as "level"
from "user" as "child_user"
join t_user as "parent_user" on "parent_user".id="child_user".parent_id
where "child_user".deleted_at isnull
)
)select * from t_user `
result := []UserData1{}
tx := d.transactionContext.PgTx
_, err := tx.Query(&result, sqlStr, userId)
return result, err
}
// func (d *UserDao) ChildUser(userId int) ([]UserData1, error) {
// sqlStr := `select "user".id,"user".parent_id ,"user".account,"user".name
// from "user"
// where "user".parent_id=?`
// result := []UserData1{}
// tx := d.transactionContext.PgTx
// _, err := tx.Query(&result, sqlStr, userId)
// return result, err
// }
// AllParentUser 获取我的全上级
func (d *UserDao) AllParentUser(userId int) ([]UserData1, error) {
sqlStr := `with
-- 人员自身以及全下级
recursive t_user as (
(
select "user".id,"user".parent_id ,"user".account,"user".name,1 as "level"
from "user"
where "user".id=? and "user".deleted_at isnull
)
union
(
select "child_user".id,"child_user".parent_id,"child_user".account,"child_user".name,
"child_user"."level" + 1 as "level"
from "user" as "parent_user"
join t_user as "child_user" on "parent_user".id="child_user".parent_id
where "parent_user".id <>0 and "parent_user".deleted_at isnull
)
)select * from t_user `
result := []UserData1{}
tx := d.transactionContext.PgTx
_, err := tx.Query(&result, sqlStr, userId)
return result, err
}