FoldersService.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace App\Services\Folder;
  3. use App\Models\File;
  4. use App\Models\Folder;
  5. use App\Models\NamingRule;
  6. use Illuminate\Database\Eloquent\Collection;
  7. use Illuminate\Support\Facades\DB;
  8. class FoldersService
  9. {
  10. public function applyNaming(string $id, string $namingRuleId): void
  11. {
  12. $folder = Folder::query()->findOrFail($id);
  13. $namingRule = NamingRule::query()->findOrFail($namingRuleId);
  14. // 子孙均需更新
  15. DB::transaction(function () use ($folder, $namingRule) {
  16. Folder::query()
  17. ->where('path', 'like', $folder->path . '%')
  18. ->update(['naming_rule_id' => $namingRule->id]);
  19. File::query()
  20. ->join('folders', 'files.folder_id', '=', 'folders.id')
  21. ->where('folders.path', 'like', $folder->path . '%')
  22. ->update(['files.naming_rule_id' => $namingRule->id]);
  23. });
  24. }
  25. public function getAllParentTree($folderId): Collection|array
  26. {
  27. $folder = Folder::query() ->select('id', 'parent_id', 'path')->findOrFail($folderId);
  28. $folderIds = explode(',', $folder->path);
  29. $allChildren = Folder::query()
  30. ->select('id', 'parent_id')
  31. ->whereIn('id', $folderIds ?? [])
  32. ->get();
  33. return make_tree($allChildren->toArray());
  34. }
  35. }