相同模型上雄辩的亲子关系 [英] Eloquent Parent-Child relationship on same model
问题描述
我有一个模型CourseModule
,每个项目都与同一个模型相关.
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();
我正在尝试创建如下所示的json输出,
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.
推荐答案
如果您的深度未知,则必须递归获取子级.
You would have to recursively get the children if you have an unknown depth like that.
另一种选择是使用嵌套集模型而不是邻接列表模型.您可以将类似baum/baum
的包用于Laravel的嵌套集.
Another option is to use the nested sets model instead of the adjacency list model. You can use something like baum/baum
package for Laravel for nested sets.
嵌套集是一种实现有序树的明智方法,该树允许进行快速的非递归查询." - https://github.com/etrepat/baum
使用此软件包,您可以使用诸如getDescendants
的方法来获取所有子代和嵌套的子代,以及使用toHierarchy
的方法来获取完整的树层次结构.
With this package you have methods like getDescendants
to get all children and nested children and toHierarchy
to get a complete tree hierarchy.
这篇关于相同模型上雄辩的亲子关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!