2017-06-26 73 views
2

我正在開發一個簡單的功課平臺。該plataform有兩個表: themes - 每個作業的主題將被保存如何用laravel製作分層表格?

id 
parent_id 
name 

works - 這裏將是每個學生

id 
theme_id 
description 

好作品,我試圖讓一個分層表。每一行都有主題,當你打開這一行時,它會顯示主題的作品,如果有一個子主題,它會顯示這個鏈接......等等!

事情是這樣的: hierarchical table

在模型中,我有:

​​

在我的控制器(我需要改善這一點):

public function index(){ 
    $themes = DB::table('themes', DB::raw('SELECT * WHERE lft IS BETWEEN parent.lft AND parent.rgt'))->get(); 
    $works = Work::all(); 

    $themes = array_map(function($theme){ 
     $theme->works = []; 
     return $theme; 
    }, $themes->toArray()); 

    foreach($themes as $theme){ 
     foreach($works as $work){ 
      if($theme->id === $work->theme_id){ 
       $theme->works[] = $work; 
      } 
     } 
    } 
    return view('dashboard.trabalhos.index', ['themes' => $themes]); 
} 

控制器的回報功能是:

array:3 [▼ 
    0 => {#275 ▼ 
    +"id": 1 
    +"parent_id": null 
    +"name": "Tema1" 
    +"description": "asdasdasd" 
    +"lft": 1 
    +"rgt": 6 
    +"depth": 0 
    +"created_at": null 
    +"updated_at": null 
    +"works": array:1 [▼ 
     0 => Work {#287 ▶} 
    ] 
    } 
    1 => {#278 ▶} 
    2 => {#279 ▶} 
] 

並在視圖,我的最後一個測試是這樣的:

<table id="asd" class="highlight"> 
    <thead> 
    <tr> 
     <th>Tema</th> 
    </tr> 
    </thead> 
    <tbody> 
    @forelse($themes as $theme) 
     @php($asd = $theme->depth) 
     @if($theme->depth === 0) 
      <tr data-tt-id="{{$theme->id}}" class="branch collapsed"> 
       <td> 

        @if(count($theme->works) > 0) 
         <?php 
         foreach($theme->works as $work){ 
          echo "nome: " . $work->title; 
         } 
         ?> 
        @endif 
        {{$theme->name}} 
       </td> 
      </tr> 
     @elseif($theme->depth > 0) 
      <tr data-tt-id="{{$theme->id}}" data-tt-parent-id="{{$theme->parent_id}}" class="branch collapsed" style="display: none;"> 

       <td> 
        {{$theme->name}} 
       </td> 
      </tr> 
     @endif 
    @empty 

    @endforelse 
    <tr></tr> 
    </tbody> 
</table> 

我使用bootstrap-treeviewtreetable嘗試,但也許我的問題是邏輯前端。有人能幫助我並給我一個亮光嗎?

+0

能你向我們展示一些你的代碼? – Drudge

+0

試試這個教程http://itsolutionstuff.com/post/laravel-5-category-treeview-hierarchical-structure-example-with-demoexample.html – manjunath

+0

你需要一些遞歸的方式 –

回答

1

您可以查看組件「kalnoy/nestedset」它是用於構建樹結構的組件,它包含所有必要的方法。 如果你會使用它,你需要指定的列添加到表像這樣

Schema::create('items', function (Blueprint $table) { 
    $table->increments('id'); 
    ... 
    NestedSet::columns($table); 
    ... 
}); 

而且可以使用所有這些組件的方法生成的樹結構是這樣的:

$root = Item::findOrFail($rootId); 
$nodes = $root->descendants->toTree($root); 

$traverse = function ($items, $prefix = '-') use (&$traverse) { 
    $html = ''; 
    foreach ($items as $item) { 
     $html .= ... (html structure) 
     $html .= $traverse($item->children, $prefix . '-'); 
    } 
    return $html; 
}; 

$html .= $traverse($nodes);