SiteAlbumFolder.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. ->map(function ($folder) use ($folders) {
  19. // 递归获取子文件夹
  20. $folder->children = self::buildTree($folders, $folder->id);
  21. return [
  22. 'id' => $folder->id,
  23. 'title' => $folder->title,
  24. 'parent_id' => $folder->parent_id,
  25. 'order' => $folder->order,
  26. 'folder_type' => $folder->folder_type,
  27. 'show_tabs' => $folder->show_tabs,
  28. 'enabled' => $folder->enabled,
  29. 'created_at' => $folder->created_at,
  30. 'updated_at' => $folder->updated_at,
  31. 'cover' => $folder->cover,
  32. 'children' => $folder->children->values()->toArray(), // 子文件夹数据
  33. ];
  34. })
  35. ->values(); // 重置键名
  36. }
  37. }