从两个表创建树结构

Create a tree structure from two tables

所以,我的问题是我需要用来自两个表的数据构建一个树。

我有以下表格:

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;
}

以上函数适用于类别,响应为:

但我想添加图层作为相应类别的子项,如下所示:

最好的方法是什么?

我建议在 Category 模型中使用 relationshipLayer 模型并预先加载它。通过这种方式,您可以获得相同的结果,但 buildTree 函数的开销更少,因为 Laravel 完成了大部分工作:

Category.php 型号

class Category extends Model
{
    // ...

    public function layers()
    {
        return $this->hasMany(Layer::class);
    }

    // ...
}

在你的控制器中:

public function index()
{
    $categories = Category::with('layers')->get();

    // ...
}

这会产生如下数组: