I have a table objectives with parent_id field
public function parent() {
return $this->belongsTo(Objective::class, 'parent_id');
}
public function directChildren() {
return $this->hasMany(Objective::class, 'parent_id');
}
public function children() {
return $this->directChildren()->with('children');
}
So when using with children it show the data recursive starting from null node parent_id
Objective::with('children')->whereNull('parent_id')->get();
So the structure is this:
[
{id: 1, parent_id: null, name: "A", children: []},
{id: 2, parent_id: null, name: "B", children: []}
{id: 3, parent_id: null, name: "C", children: [
{id: 4, parent_id: 3, name: "D", children: [
{id: 5, parent_id: 4, name: "E", children: []}
]},
{id: 6, parent_id: 3, name: "F", children: []}
]}
]
How can I see all the parents up and generate the structure ? Ex: starting from node E and show it like this:
[
{id: 3, parent_id: null, name: "C", children: [
{id: 4, parent_id: 3, name: "D", children: [
{id: 5, parent_id: 4, name: "E", children: []}
]},
]}
]