【问题标题】:How to display tree sturcture recursively in laravel blade?如何在 laravel 刀片中递归显示树结构?
【发布时间】:2017-10-28 15:46:34
【问题描述】:

我有一个数组输出是这样的树状结构:

在这里,我有一个具有父子关系的数据库表,例如:

public function up()
{
     Schema::create('trees', function (Blueprint $table) {
         $table->increments('id');
         $table->integer('parent_id')->unsigned()->nullable();
         $table->string('name');
         $table->integer('has_child');
         $table->integer('depth');
         $table->timestamps();
         $table->foreign('parent_id')->references('id')->on('trees')->onDelete('cascade');
    }
}

这里,

深度定义树中从根开始的深度,parent_id 指同一张表中的父级,has_child 定义子级的存在。对于叶子,has_child 为零,而顶部 parent_id 为空。

深度可以是最大为 5 的任何值。 在上述情况下,只有 2 个用于测试目的。

这是我的示例数据库记录:

我在控制器中递归地得到了上面的树结构:

    public function getChilds($d){
        $tree = array();
        $children = array();
        $tree['parent'] = $d->toArray();
        if($d->has_child==1){
            $data = Tree::where('parent_id',$d->id)->get();
            foreach ($data as $d) {
                $first = $this->getChilds($d);
                array_push($children, $first);
            }
        }
        $tree['children'] = $children;
        return $tree;
    }

    public function getTree(){
        $tree = array();
        $data = Tree::where('parent_id',null)->get();
        foreach ($data as $d) {
            $first = $this->getChilds($d);
            array_push($tree, $first);
        }
        return view('tree',compact('tree'));
    }

现在,

我想在树状结构中显示这些数据。但是,由于深度不同,我无法确定我应该去的深度。

有什么方法可以在 laravel Blade 中递归显示这个结构?

预期的输出是这样的:

One0

    One0Two0

        One0Two0Three0

        One0Two0Three1

    One0Two1

        One0Two1Three0

        One0Two1Three1

    One0Two2

        One0Two2Three0

        One0Two2Three1

感谢任何形式的帮助。

【问题讨论】:

    标签: arrays laravel recursion


    【解决方案1】:

    我会推荐你​​ laravel-nestedset 包,它会让你的生活变得非常轻松。请按照包文档创建你的表结构,检索、保存和更新递归数据将非常容易。这是包链接。

    https://github.com/lazychaser/laravel-nestedset

    【讨论】:

    • 我已经花了一点时间来查看这个,但我不明白这些包在我的问题中的使用
    • 我用过这个但是还是不知道怎么把树结构传给视图...
    • 你想做什么来创建菜单或其他东西?
    猜你喜欢
    • 2016-12-04
    • 2019-11-25
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 2019-06-28
    相关资源
    最近更新 更多