gpt4 book ai didi

php - 递归获取树的所有 parent 和 child

转载 作者:可可西里 更新时间:2023-11-01 07:05:55 26 4
gpt4 key购买 nike

我有一个 MySQL 表作为

+--------------------+--------------------+--------------------+
| Id | parent_id | title |
+--------------------+--------------------+--------------------+
| 1 | 0 | Student Management |
|--------------------|--------------------|--------------------|
| 2 | 0 | Staff Management |
|--------------------|--------------------|--------------------|
| 3 | 1 | Add Student |
|--------------------|--------------------|--------------------|
| 4 | 1 | View Students |
|--------------------|--------------------|--------------------|
| 5 | 2 | Add Staff |
|--------------------|--------------------|--------------------|
| 6 | 2 | View Staff |
|--------------------|--------------------|--------------------|
| 7 | 4 | Delete |
|--------------------|--------------------|--------------------|
| 8 | 5 | Copy |
+--------------------+--------------------+--------------------+

我想在我看来递归地超越 as。

期望的输出

+-------------------------------+------------------------------+
| Student Mangement | Staff Management |
| Add Student | Add Staff |
| View Student | Copy |
| Delete | View Staff |
+-------------------------------+------------------------------+

我想把上面的MySQL表作为我上面定义的结构

我的get方法是

public function get()
{
$categories = Categories::where('parent_id', '=', 0)->get();
$permission = Categories::pluck('title','id')->all();
return view('create-role')->with(compact('categories'));
}

用上面的方法,我让 parent 在你看来是

@foreach($categories as $category)
<li>
{{ $category->title }}
</li>
@endforeach

输出为

学生管理

员工管理

请帮助我如何递归地获得上述结构。

最佳答案

首先定义模型中的关系

public function children() {
return $this->hasMany(Category::class, 'parent_id', 'id');
}

public function parent() {
return $this->belongsTo(Category::class, 'parent_id', 'id');
}

那在你看来,我不知道你有多少个子关卡。但是有两种方法:

1- 最简单的方法
如果你知道,你永远不会超过 3 个级别,只需在你的 View 中嵌套 3 个 foreach

先急切的查询

$categories = Category::with('children')->get(); //save you some queries 

@foreach($categories as $category)
@if( $category->children )
@foreach($category->children as $level2)
@if($level2->children)
@foreach($level2->children as $level3)
@if($level3->children)
//another foreach
@endif
{{ $level3->title }}
@foreach
@endif
{{ $level2->title }}
@endforeach
@endif

{{ $category->title }}
@endforeach

2-实际的递归方式。
这是实验性的,未经测试
定义递归关系

public function recursiveChildren() {
return $this->children()->with('recursiveChildren');
//It seems this is recursive
}

关于php - 递归获取树的所有 parent 和 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42779256/

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