如何使用laravel创建分层表?

时间:2017-06-26 03:34:12

标签: javascript jquery laravel treeview hierarchical-data

我正在开发一个简单的学校作业。该平台有两个表:  themes - 保存每份工作的主题

id
parent_id
name

works - 这将是每个学生的作品

id
theme_id
description

好吧,我试图制作一个分层表。每行都有主题,当你打开行时,它会显示主题的作品,如果有一个子主题,它会显示这个链接...等等!

这样的事情: hierarchical table

在模特中,我有:

public function childs() {
    return $this->hasMany(self::class,'parent_id','id') ;
}

在我的控制器中(我需要改进):

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,但也许我的问题是前端的逻辑。有人可以帮助我并给我一个亮点吗?

1 个答案:

答案 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);
相关问题