QaLoader.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace App\Services\Markup\Resolve;
  3. use App\Models\Discussion;
  4. /**
  5. * qa 模板:按 id 取问答话题的标题与挂载对象,一次查完。
  6. */
  7. final class QaLoader extends Loader
  8. {
  9. /** @var array<string, true> */
  10. private array $pending = [];
  11. /** @var array<string, Discussion|null> */
  12. private array $results = [];
  13. public function request(string $id): void
  14. {
  15. if ($id !== '' && ! array_key_exists($id, $this->results)) {
  16. $this->pending[$id] = true;
  17. }
  18. }
  19. public function result(string $id): ?Discussion
  20. {
  21. return $this->results[$id] ?? null;
  22. }
  23. public function hasPending(): bool
  24. {
  25. return $this->pending !== [];
  26. }
  27. public function load(): void
  28. {
  29. $ids = array_keys($this->pending);
  30. $this->pending = [];
  31. $found = Discussion::whereIn('id', $ids)->get(['id', 'title', 'res_id', 'res_type'])
  32. ->keyBy(fn (Discussion $row) => (string) $row->id);
  33. foreach ($ids as $id) {
  34. $this->results[$id] = $found->get($id);
  35. }
  36. }
  37. }