FoldersService.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. if ($folder->naming_rule_id == $namingRule->id) {
  15. return;
  16. }
  17. // 子孙均需更新
  18. DB::transaction(function () use ($folder, $namingRule) {
  19. Folder::query()
  20. ->where('path', 'like', $folder->path . '%')
  21. ->update(['naming_rule_id' => $namingRule->id]);
  22. File::query()
  23. ->join('folders', 'files.folder_id', '=', 'folders.id')
  24. ->where('folders.path', 'like', $folder->path . '%')
  25. ->update(['files.naming_rule_id' => $namingRule->id, 'naming_rules' => null]);
  26. });
  27. }
  28. public function getAllParentTree($folderId): Collection|array
  29. {
  30. $folder = Folder::query() ->select('id', 'name', 'parent_id', 'path')->findOrFail($folderId);
  31. $folderIds = explode(',', $folder->path);
  32. $allChildren = Folder::query()
  33. ->select('id', 'name', 'parent_id')
  34. ->whereIn('id', $folderIds ?? [])
  35. ->get();
  36. return make_tree($allChildren->toArray());
  37. }
  38. }