The following example is used to populate a tree and use a table with a parent_id column.
The data is obtained with a recursive query.
$data = [{
"id": 1,
"name": "parent 1"
"note": "note 1",
}, {
"id": 2,
"name": " parent 2",
"note": "note 2",
"children": [{
"id": 21,
"name": "child A of 2",
"note": "note A of 2",
},{
"id": 22,
"name": "child B of 2",
"note": "note B of 2",
},{
"id": 23,
"name": "child C of 2",
"note": "note C of 2",
"children": [{
"id": 231,
"name": "child A of 23",
"note": "note A of 23",
"children": [{
"id": 2311,
"name": "child A of 231",
"note": "note A of 231",
"children": []
}]
}]
}]
}];
And the query:
$myData= Hierarchy::whereNull('parent_id')
->with('children')
->get();
So far so good.
Problem to solve:
It is necessary to obtain a simple (non-hierarchical) list of the id and name attributes of the parents and children.
Example:
"id": 1,
"name": "parent 1",
"id": 2,
"name": " parent 2",
"id": 21,
"name": "child A of 2",
"id": 23,
"name": "child C of 2",
"id": 231,
"name": "child A of 23",
"id": 2311,
"name": "child A of 231"
While this can be solved on the client side with javascript, I intended to do it with eloquent or PHP functions.
I made some attempts with the array_walk() and array_walk_recursive() PHP functions (without success).
Is there any way to solve with eloquent, bearing in mind that the number of children nodes can be infinite?
Thanks.
EDITED:
Example attempt with array_walk_recursive() PHP function
public function getList()
{
$myData= Hierarchy::whereNull('parent_id')
->with('children')
->get();
$data = array_walk_recursive($myData, "self::myFunction");
return response()->json(['success' => true, "data" => $data]);
}
public function myFunction($item, $key){
???
}
CodePudding user response:
You can use the API Resouce recursively or use the recursive function to generate the hierarchy array.
Example with recursive function:
function makeHierarchy($values)
{
$result = [];
foreach($values as $item) {
$result[] = [
'id' => $item->id,
'name' => $item->name,
'children' => makeHierarchy($item->children),
];
}
return $result;
}
$values = Hierarchy::whereNull('parent_id')->with('children')->get();
$hierarchical = makeHierarchy($values);
If you want to get all values as a flat list:
$values = Hierarchy::get();
$result = [];
foreach($values as $item) {
$result[] = [
'id' => $item->id,
'name' => $item->name,
];
}
# now the result contains all the parents and children in a flat list
In the cleaner way:
$result = Hierarchy::select(['id', 'name'])->all();