【发布时间】:2020-04-28 23:07:08
【问题描述】:
所以,我的问题是我需要用两个表中的数据构建一棵树。
我有以下表格:
Category:
| id | parent_id | name |
|----|-----------|----------------|
| 1 | null | Category 1 |
| 2 | 1 | Category 1.1 |
| 3 | 2 | Category 1.1.1 |
| 4 | null | Category 2 |
| 5 | 4 | Category 2.1 |
| 6 | null | Category 3 |
Layer:
| id | category_id | name |
|----|-------------|---------|
| 1 | 2 | Layer 1 |
| 2 | 2 | Layer 2 |
| 3 | 3 | Layer 3 |
| 4 | 4 | Layer 4 |
| 5 | 4 | Layer 5 |
| 6 | 5 | Layer 6 |
我的类别模型:
class Category extends Model
{
public function parent()
{
return $this->belongsTo('App\Category', 'parent_id');
}
public function childrens()
{
return $this->hasMany('App\Category', 'parent_id', 'id');
}
public function layers()
{
return $this->hasMany('App\Layer', 'category_id', 'id');
}
}
图层模型:
class Layer extends Model
{
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
}
我正在使用以下函数来构建类别树:
public function index()
{
$categories = Category::all();
$layers = Layer::all();
return $this->buildTree($categories->toArray(), null);
}
function buildTree($categories, $parent_id)
{
$categoriesTree = [];
foreach ($categories as $category) {
$category['folder'] = true;
if ($category['parent_id'] == $parent_id) {
$childrens = $this->buildTree($categories, $category['id']);
if ($childrens) {
$category['childrens'] = $childrens;
}
$categoriesTree[] = $category;
}
}
return $categoriesTree;
}
上述函数适用于类别,响应为:
- 类别 1
- 1.1 类
- 1.1.1 类
- 1.1 类
- 类别 2
- 2.1 类
- 第 3 类
但我想将图层添加为相应类别的子级,如下所示:
-
第 1 类
-
1.1 类
-
类别 1.1.1
- 第 3 层
- 第 1 层
- 第 2 层
-
类别 1.1.1
-
1.1 类
-
第 2 类
-
2.1 类
- 第 6 层
- 第 4 层
- 第 5 层
-
2.1 类
- 第 3 类
最好的方法是什么?
【问题讨论】:
标签: php laravel eloquent tree treeview