使用 blade 来自 laravel collection 的输出文件夹树

Output folder tree using blade from laravel collection

假设我有以下 laravel collection:

[
 {id: 1, name: 'Home', folder_id: null},
 {id: 2, name: 'Documents', folder_id: 1},
 {id: 3, name: 'Media', folder_id: 1 },
 {id: 4, name: 'Photos', folder_id: 3},
 {id: 5, name: 'Videos', folder_id: 3},
 {id: 6, name: 'Invoices', folder_id: 2},
 {id: 7, name: 'Games', folder_id: 1}
]

folder_id是外键是一行直接parent.

我想遍历 collection 并使用 blade 模板引擎创建如下所示的文件夹树:

collection 中的每个元素都是实例文件夹,定义了以下 eloquent 关系:

public function folder(){
    return $this->belongsTo(Folder::class);
}

public function folders(){
    return $this->hasMany(Folder::class);
}

将此添加到文件夹模型 class

public function children()
{
    return $this->hasMany(Folder::class,'folder_id','id');
}

public function parent()
{
    return $this->belongsTo(Folder::class,'id','folder_id');
}

然后在controlle中传递所有给view

return view('view')->with(['folders'=>Folder::with('parent','children')->all()]);

而且在视图中这将起作用

<ul>
 @foreach($folders as $folder)
 {
   @foreach($folder->children as $child)
       //you can get child parent via $child->parent
   @endforeach

   //do whatever you want
 }
</ul>

经过几个小时的 while 循环和其他愚蠢的操作,我终于意识到了 blade 的部分功能。

首先,我定义初始循环并输出所有顶级文件夹,即 folder_id(父文件夹 ID)为 null 的文件夹。

@foreach($folders as $folder)
        @if($folder->folder_id == null)
            @include('folder', $folder)
        @endif
@endforeach

在 folder.blade.php 部分中,我有以下代码:

<div class="folder" style="padding-left: 10px">
    <div class="name">{{ $folder->name }}</div>
    @if($folder->folders)
        @foreach($folder->folders as $child_folder)
            @include('folder', ['folder' => $child_folder])
        @endforeach
    @endif
</div>

在局部中,我检查给定的文件夹是否有子文件夹,如果有,我再次为每个文件夹的子文件夹包含部分。