2017-05-28 275 views
1

我有一个数组输出是树状结构是这样的:如何在laravel blade中递归显示树结构?

enter image description here

在这里,我有喜欢的父子关系的数据库表:

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个用于测试目的。

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

enter image description here

我在控制了上述树形结构递归为:

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 

任何形式的帮助表示赞赏。

回答

0

我会推荐你​​laravel-nestedset包,这将使你的生活变得非常简单,请按照包文档来创建你的表结构,检索,保存和更新递归数据将非常简单。这里是包链接。

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

+0

我已经花一点时间来查看这一点,但我还没有理解我的问题,使用这些包 –