user_dao.go 1.6 KB
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=3422174102828544
		)
		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 
		)
	)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
}