我有一个模型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,它工作:) –