I have a model CourseModule
, and each of the items are related to the same 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.
CourseModule::with('children')->get();
I'm trying to create a json output like the following,
[ { "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.
To model a parent-child hierarchy, you create attributes, map them to the relational data source and identify which attributes represent the parent key and child key. The child key also acts as the member key. The top level member in a parent-child hierarchy is determined as the member whose parent is Null.
have certain qualities that remain constant. They are built on safety, unconditional love, mutual respect, acceptance and flexibility.
A form of filial therapy, child-parent relationship theory (CPRT) teaches parents to use child-centered play therapy (CCPT) skills with their children. Based on attachment theory, CPRT espouses that a secure bond between parent and child is mandatory for children's healthy development.
You should use with('children')
in the children relation and with('parent')
in the parent relations.
For your code to be recursive:
public function parent() { return $this->belongsTo('App\CourseModule','parent_id')->where('parent_id',0)->with('parent'); } public function children() { return $this->hasMany('App\CourseModule','parent_id')->with('children'); }
Note: Make sure your code has some or the other exit conditions otherwise it will end up in a never ending loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With