Skip to content

Instantly share code, notes, and snippets.

@gexchai
Created August 9, 2018 01:18
Show Gist options
  • Select an option

  • Save gexchai/ab25b17e5f33c5bce5ad1d5ef064e7a9 to your computer and use it in GitHub Desktop.

Select an option

Save gexchai/ab25b17e5f33c5bce5ad1d5ef064e7a9 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
/**
* DB structure if we use Mysql
DROP TABLE IF EXISTS `employees`;
CREATE TABLE `employees` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`manager_id` int(10) unsigned DEFAULT NULL,
`name` varchar(512) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
*/
/**
* Recursive sql if we using Mysql 8 +
* This will avoid printing out any unrelated employee
WITH RECURSIVE EmployeeStuct AS (
SELECT * FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT m.* FROM employees AS m JOIN EmployeeStuct AS t ON m.manager_id = t.id
)
SELECT * FROM EmployeeStuct;
*/
type Employee struct {
Id int
ManagerId int
Name string
}
type EmployeeTree struct {
Id int
ManagerId int
Name string
son []EmployeeTree
}
var allEmployees = []Employee{
Employee{100, 150, "Alan"},
Employee{220, 100, "Martin"},
Employee{150, 0, "Jamie"},
Employee{275, 100, "Alex"},
Employee{400, 150, "Steve"},
Employee{190, 400, "David"},
}
func main() {
arr := recursiveTree(allEmployees, 0)
fmt.Println(arr)
}
// function to group the employees accordingly to their manager
func recursiveTree(allEmployee []Employee, ManagerId int) []EmployeeTree {
var arr []EmployeeTree
for _, v := range allEmployee {
if ManagerId == v.ManagerId {
ctree := EmployeeTree{}
ctree.Id = v.Id
ctree.ManagerId = v.ManagerId
ctree.Name = v.Name
sonE := recursiveTree(allEmployee, v.Id)
ctree.son = sonE
arr = append(arr, ctree)
}
}
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment