【问题标题】:Create a tree structure from two tables从两个表创建树结构
【发布时间】: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 类
  • 类别 2
    • 2.1 类
  • 第 3 类

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

  • 第 1 类
    • 1.1 类
      • 类别 1.1.1
        • 第 3 层
      • 第 1 层
      • 第 2 层
  • 第 2 类
    • 2.1 类
      • 第 6 层
    • 第 4 层
    • 第 5 层
  • 第 3 类

最好的方法是什么?

【问题讨论】:

    标签: php laravel eloquent tree treeview


    【解决方案1】:

    我建议在您的 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();
    
        // ...
    }
    

    这会产生一个像这样的数组:

    【讨论】:

    • 我尝试过这种方法,但效果不佳。结果如下:pastebin.com/i2siU7Bt 谢谢!
    • 您的控制器方法似乎缺少buildTree() 函数。
    • 正是这个!工作正常(需要一些小调整,但没有什么我不能做的)。谢谢!
    • 很高兴有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2017-04-18
    相关资源
    最近更新 更多