SiteAlbumFolder.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. //
  39. public static function getfolderTreeIds($title)
  40. {
  41. // 获取所有文件夹记录并预加载子级
  42. $folders = self::with('children')->get()->toArray();
  43. $ids = [];
  44. // 递归遍历查找目标标题的节点及其子节点
  45. array_walk($folders, function ($folder) use ($title, &$ids) {
  46. if ($folder['title'] == $title) {
  47. self::collectIdsRecursive($folder, $ids);
  48. }
  49. });
  50. return array_unique($ids); // 去重后返回
  51. }
  52. /**
  53. * 递归收集节点及其子节点ID
  54. */
  55. protected static function collectIdsRecursive($node, &$ids)
  56. {
  57. $ids[] = $node['id'];
  58. if (!empty($node['children'])) {
  59. array_walk($node['children'], function ($child) use (&$ids) {
  60. self::collectIdsRecursive($child, $ids);
  61. });
  62. }
  63. }
  64. }