2017-05-28 34 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

我已經花一點時間來查看這一點,但我還沒有理解我的問題,使用這些包 –