如何使用laravel构建文件夹层次结构?

如何使用laravel构建文件夹层次结构?,laravel,Laravel,这是我的模型: <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Folder extends Model { protected $with = ['children']; public function children() { return $this->hasMany('App\Models\Folder','parent_id')/*->select('t

这是我的模型:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Folder extends Model
{
protected $with = ['children'];

public function children()
{
    return $this->hasMany('App\Models\Folder','parent_id')/*->select('title','path','size','ext','isFolder')*/;
}

public function user()
{
    return $this->belongsTo('App\User','user_id');
}

public static function tree() {

    return static::with(implode('.', array_fill(0, 4, 'children')))->where('parent_id', '=', NULL)->get();

}
}
我正在尝试显示每个文件夹及其内容,无论是文件还是其他目录,有没有一种方法可以做到这一点,而不必为每个级别执行foreach循环?

这可以用。如果您也熟悉我将要编写的代码,那么将很容易理解。安维,一切都用评论来解释

/**
*递归检索构建树的相关子级。
*注意!此范围可能会导致许多性能问题。尤其是有很多孩子/侄子的时候
* 
*@param Buider$query
*@param integer$deep
*@param integer$index
*@returnbuilder
*/
公共函数scopeTree($query,$deep,$index=0){
//增量指数
$index++;
//当前模型是root,让我们查找基本case的id。
$id=$this->getKey();
//现在构建递归嵌套查询
return$query->whereHas('children',函数($query)use($deep,$index,$id){
//如果deep低于index,则意味着我们必须向树中添加一个节点
如果($deep<$index){
//递归
$query->tree($deep,$index);
}否则{
//基本情况
$query->where('parent_id','=',$id);
}
});
}
无论如何,这个函数可能会导致很多性能问题,所以如果数据库中有很多记录,最好不要“太深”

 $folders = Folder::tree();