首页 > 解决方案 > 如何制作:文件夹中的文件夹...到 Laravel 中的无穷大

问题描述

我需要选择在文件夹中创建新文件夹,然后在新文件夹中创建新文件夹......等等无限期。就像我们可以在桌面上完成一样。我在文档中找不到类似的东西。我想知道我是否可以在文件夹模型中建立关系:

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

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

这行得通吗?

我也想知道,数据库中的文件夹表是什么样的?我们可以有:

 $table->unsignedBigInteger('folder_id');
            $table->foreign('folder_id')
                ->references('id')
                ->on('folder')
                ->onDelete('cascade');

另外,我必须在 API 路由上做所有事情,所以我想知道,/folder/{folder}每次创建新文件夹时如何添加?

标签: laravelvue.jseloquent

解决方案


您显示的方式是定义文件夹之间的一对多关系。这应该足够了,因为一个文件夹可能只有 1 个父文件夹。我建议使用以下关系命名:

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

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

不过,这条路线会有点棘手:

Route::get('/folder/{folder}', function ($folder) {
   $hierarchy = explode('/', $folder);
   $root = array_shift($hierarchy);
   $currentFolder = Folder::where('name', $root)->doesntHave('parentFolder')->firstOrFail(); // Root folder has no parents
   while (!empty($hierarchy)) {
       $currentFolder = Folder::where('name', array_shift($hierarchy))
                 ->whereHas('parentFolder', function ($q) use ($currentFolder) { 
                       $q->where('id', $currentFolder->id); 
                  })->firstOrFail(); 
   }
   // $currentFolder should be the correct folder
   
   
})->where([ 'folder' => '.*' ]); // {folder} can be any string

如果您想模拟类似 Linux 的系统,您可以随时修改上述内容以添加一个名为/所有文件夹根目录的文件夹。这将要求您先获取此文件夹,然后再循环获取目录结构


推荐阅读