laravel - 如何制作:文件夹中的文件夹...到 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}
每次创建新文件夹时如何添加?
解决方案
您显示的方式是定义文件夹之间的一对多关系。这应该足够了,因为一个文件夹可能只有 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 的系统,您可以随时修改上述内容以添加一个名为/
所有文件夹根目录的文件夹。这将要求您先获取此文件夹,然后再循环获取目录结构
推荐阅读
- c# - 除了外键整数属性之外添加导航属性时,Entity Framework 正在我的表中创建两个 Id 字段
- ios - 如何让移动应用程序在中国安装和运行?应用程序可以在不使用 VPN 的情况下运行吗?
- dbus - 通过 Bluez DBus API 的设备连接/断开通知
- webrtc - 需要帮助我的公共 IP 地址的 Coturn 配置
- echarts - 如何在 echarts 图形元素上捕获鼠标右键单击事件?
- teradata - 如何在 teradata 中创建每个用户都可以访问的表
- python - 类激活图 (CAM) 的池化梯度问题
- google-apps-script - 带有 Gmail 的 Google Apps 脚本:搜索、重命名和转发特定邮件
- vue.js - 使用 Vue Web 组件访问 Webpack 外部库
- codeigniter - 使用数据库驱动程序时,Codeigniter 会话未存储在数据库中