相同模型上雄辩的亲子关系 [英] Eloquent Parent-Child relationship on same model

查看:73
本文介绍了相同模型上雄辩的亲子关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型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.

维基百科-嵌套集模型

Baum-Laravel雄辩的ORM的嵌套集模式

在MySQL中管理分层数据

这篇关于相同模型上雄辩的亲子关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆