I am trying to create a company organisation tree but I just can't get things working.
I am hoping some of you clever people will shine some light on my mistakes.
My database only has a few row and looks like this for testing...
- id, parent_id, client_id, department_id
- 1, 0, 1, 4
- 2, 1, 1, 4
- 3, 2, 1, 4
- 4, 0, 1, 4
All i can ever seam to get is this
array:1
["children" => array:2
[0 => array:2
[
"id" => 0
"name" => "Marketing Director"
]
1 => array:2
[
"id" => 0
"name" => "Accounts Director"
]
]
]
But what I actually want is the parent child structure
Parent > Child > Child etc etc...
Here's my code so far...
public static function generateOrgTree($clientid, $parent)
{
$all_cats = DB::table('client_roles_rel')
->join('client_job_roles', 'client_job_roles.role_id', '=', 'client_roles_rel.role_id')
->join('client_departments', 'client_departments.department_id', '=', 'client_roles_rel.department_id')
->where('client_roles_rel.client_id', '=', $clientid)
->orderby('client_roles_rel.rel_id', 'asc')
->get();
$tree = [];
foreach ($all_cats as $cats)
{
$pid = $cats->parent_id;
$id = $cats->id;
$department = $cats->department_name;
if($pid == '0')
{
$tree['children'][] = ['id' => $pid, 'name' => $rolename];
}
else
{
if($pid == $parent)
{
$children = General::generateOrgTree($clientid, $id);
$pid = $cats->parent_id;
$id = $cats->id;
$department = $cats->department_name;
$tree['children'][] = ['id' => $pid, 'name' => $rolename];
}
}
}
//dd(json_encode($tree));
return $tree;
}