· 8 years ago · Aug 09, 2018, 03:32 AM
1package main
2
3import (
4 "fmt"
5)
6
7/**
8 * DB structure if we use Mysql
9 DROP TABLE IF EXISTS `employees`;
10 CREATE TABLE `employees` (
11 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
12 `manager_id` int(10) unsigned DEFAULT NULL,
13 `name` varchar(512) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
14 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
15 `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
16 PRIMARY KEY (`id`)
17) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
18*/
19
20/**
21 * Recursive sql if we using Mysql 8 +
22 * This will avoid printing out any unrelated employee
23WITH RECURSIVE EmployeeStuct AS (
24 SELECT * FROM employees WHERE manager_id IS NULL
25 UNION ALL
26 SELECT m.* FROM employees AS m JOIN EmployeeStuct AS t ON m.manager_id = t.id
27)
28SELECT * FROM EmployeeStuct;
29*/
30
31type Employee struct {
32 Id int
33 ManagerId int
34 Name string
35}
36type EmployeeTree struct {
37 Id int
38 ManagerId int
39 Name string
40 son []EmployeeTree
41}
42
43var allEmployees = []Employee{
44 Employee{100, 150, "Alan"},
45 Employee{220, 100, "Martin"},
46 Employee{150, 0, "Jamie"},
47 Employee{275, 100, "Alex"},
48 Employee{400, 150, "Steve"},
49 Employee{190, 400, "David"},
50}
51
52func main() {
53 arr := recursiveTree(allEmployees, 0)
54 fmt.Println(arr)
55
56}
57
58// function to group the employees accordingly to their manager
59func recursiveTree(allEmployee []Employee, ManagerId int) []EmployeeTree {
60 var arr []EmployeeTree
61 for _, v := range allEmployee {
62 if ManagerId == v.ManagerId {
63 ctree := EmployeeTree{}
64 ctree.Id = v.Id
65 ctree.ManagerId = v.ManagerId
66 ctree.Name = v.Name
67
68 sonE := recursiveTree(allEmployee, v.Id)
69 ctree.son = sonE
70 arr = append(arr, ctree)
71 }
72 }
73 return arr
74}