gpt4 book ai didi

php - 同一模型上 Eloquent 亲子关系

转载 作者:IT王子 更新时间:2023-10-29 00:11:57 28 4
gpt4 key购买 nike

我有一个模型 CourseModule,每个项目都与同一个模型相关。

数据库结构:

enter image description here

模型中的关系:

    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": []
}
]
}
]
}
]
}
]

我不明白如何获取内部子对象。

最佳答案

您应该在子关系中使用 with('children')和父关系中的 with('parent')

为了你的代码是递归的:

public function parent()
{
return $this->belongsTo('App\CourseModule','parent_id')->where('parent_id',0)->with('parent');
}

public function children()
{
return $this->hasMany('App\CourseModule','parent_id')->with('children');
}

注意:确保您的代码具有某些或其他退出条件,否则它会陷入永无止境的循环。

关于php - 同一模型上 Eloquent 亲子关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34758965/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com