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('AppCourseModule','parent_id')->where('parent_id',0);
}
public function children()
{
return $this->hasMany('AppCourseModule','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.
See Question&Answers more detail:
os