假设我有以下laravel集合:
[
{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是外键,是直接父级的一行。
我想遍历集合并使用刀片模板引擎创建一个看起来像这样的文件夹树:
集合中的每个元素都是实例文件夹,其中定义了以下雄辩关系:
public function folder(){
return $this->belongsTo(Folder::class);
}
public function folders(){
return $this->hasMany(Folder::class);
}
答案 0 :(得分:0)
将此添加到文件夹模型类
public function children()
{
return $this->hasMany(Folder::class,'folder_id','id');
}
public function parent()
{
return $this->belongsTo(Folder::class,'id','folder_id');
}
然后在controlle中传递all来查看
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>
答案 1 :(得分:0)
经过几个小时的循环和其他愚蠢,我终于意识到了刀片部分的力量。
首先,我定义了初始循环并输出所有顶级文件夹,即那些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>
在部分中,我检查给定文件夹是否有子项,如果有,我再次为每个文件夹的子项包含部分文件。