I have a model CourseModule
, and each of the items are related to the same model.
Database Structure:
Relation in Model:
public function parent()
{
return $this->belongsTo('App\CourseModule','parent_id')->where('parent_id',0);
}
public function children()
{
return $this->hasMany('App\CourseModule','parent_id');
}
I tried the following, but it returns only a single level of relation.
Tried:
CourseModule::with('children')->get();
I'm trying to create a json output like the following,
Expected Output:
[
{
"id": "1",
"parent_id": "0",
"course_id": "2",
"name": "Parent",
"description": "first parent",
"order_id": "1",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00",
"children": [
{
"id": "2",
"parent_id": "1",
"course_id": "2",
"name": "Child 1",
"description": "child of parent",
"order_id": "2",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00",
"children": [
{
"id": "3",
"parent_id": "2",
"course_id": "2",
"name": "Child2",
"description": "child of child1",
"order_id": "2",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00",
"children": [
{
"id": "4",
"parent_id": "3",
"course_id": "2",
"name": "Child 3",
"description": "child of child 2",
"order_id": "2",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00",
"children": []
}
]
}
]
}
]
}
]
I don't understand how to get the inner child objects.
You would have to recursively get the children if you have an unknown depth like that.
Another option is to use the nested sets model instead of the adjacency list model. You can use something like
baum/baum
package for Laravel for nested sets.With this package you have methods like
getDescendants
to get all children and nested children andtoHierarchy
to get a complete tree hierarchy.Wikipedia - Nested Set Model
Baum - Nested Set pattern for Laravel's Eloquent ORM
Managing Hierarchical Data in MySQL
You can always create your own recursive function, in my case I do as the code as follow.
You should use
with('children')
in the children relation andwith('parent')
in the parent relations.For your code to be recursive:
Note: Make sure your code has some or the other exit conditions otherwise it will end up in a never ending loop.
Model Function:
Controller Function:
here is the answer that can help you
I think you you have to do it recursively to retrieve whole tree:
Recursive function
This may help you according to your requirement,