SiteAlbumFolder.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Collection;
  5. class SiteAlbumFolder extends Model
  6. {
  7. protected $table = 'site_album_folder';
  8. // 定义与自身的关系,用于获取子文件夹
  9. public function children()
  10. {
  11. return $this->hasMany(SiteAlbumFolder::class, 'parent_id');
  12. }
  13. // 递归构建父子关系树
  14. public static function buildTree(Collection $folders, $parentId = null)
  15. {
  16. return $folders
  17. ->where('parent_id', $parentId) // 过滤出当前层级的文件夹
  18. ->sortByDesc('order') // 按顺序排序
  19. ->map(function ($folder) use ($folders) {
  20. // 递归获取子文件夹
  21. $folder->children = self::buildTree($folders, $folder->id);
  22. return [
  23. 'id' => $folder->id,
  24. 'title' => $folder->title,
  25. 'parent_id' => $folder->parent_id,
  26. 'order' => $folder->order,
  27. 'folder_type' => $folder->folder_type,
  28. 'show_tabs' => $folder->show_tabs,
  29. 'enabled' => $folder->enabled,
  30. 'created_at' => $folder->created_at,
  31. 'updated_at' => $folder->updated_at,
  32. 'cover' => $folder->cover,
  33. 'children' => $folder->children->values()->toArray(), // 子文件夹数据
  34. ];
  35. })
  36. ->values(); // 重置键名
  37. }
  38. }