我有一個模型CourseModule
,並且每個項目都與相同的模型有關。在同一模型上雄辯的親子關係
數據庫結構:
關係在型號:
public function parent()
{
return $this->belongsTo('App\CourseModule','parent_id')->where('parent_id',0);
}
public function children()
{
return $this->hasMany('App\CourseModule','parent_id');
}
我嘗試以下,但它僅返回關係的一個級別。
嘗試:
CourseModule::with('children')->get();
我試圖創建類似下面的JSON輸出,
預期輸出:
[
{
"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": []
}
]
}
]
}
]
}
]
我不明白怎麼弄內子對象。
嗨,'CourseModule :: whereId($ ID) - >第一個() - > getDescendantsAndSelf() - > toHierarchy()'只返回單個節點,我應該有對模型的任何變化,我正在用頂部 –
中顯示的單個表格工作謝謝@lagbox,它工作:) –