我有一个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 |
+--------------------+--------------------+--------------------+
我希望以递归方式在我的视图中得到上述.
期望的输出
+-------------------------------+------------------------------+
| Student Mangement | Staff Management |
| Add Student | Add Staff |
| View Student | Copy |
| Delete | View Staff |
+-------------------------------+------------------------------+
我希望将MySQL表格作为上面定义的结构
我的创建方法是
public function create()
{
$categories = Categories::where('parent_id', '=', 0)->get();
$permission = Categories::pluck('title','id')->all();
return view('create-role')->with(compact('categories'));
}
通过上述方法,我将父母视为
@foreach($categories as $category)
{{ $category->title }}
@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个级别,只需在你的视图中嵌套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,mysql,recursion,laravel
来源: https://codeday.me/bug/20190522/1154395.html