TipitakaBookService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\BookTitle;
  4. use App\Models\PaliText;
  5. use Illuminate\Contracts\Database\Eloquent\Builder;
  6. use Illuminate\Support\Collection;
  7. /**
  8. * 按 `pcd_book_id`(`book_titles.sn`)批量取书的基本信息:书名所在段、书名、tag、层级。
  9. *
  10. * 检索结果按书汇总时用(逐词检索的 /aggregate、页码检索),一次两条查询,不逐本查。
  11. */
  12. class TipitakaBookService
  13. {
  14. /** 书的 tag → layer(同 TipitakaChapterService),一本书有多个时按这个顺序取第一个 */
  15. private const LAYER_TAGS = ['mūla' => 'mula', 'aṭṭhakathā' => 'atthakatha', 'ṭīkā' => 'tika', 'añña' => 'anna'];
  16. /**
  17. * 结果以 book_id 为键;book_titles 里没有的书不在其中。
  18. *
  19. * @param iterable<int> $bookIds pcd_book_id
  20. * @return Collection<int, array{book_id: int, book: int, para: int, title: string, layer: string|null, tags: list<string>}>
  21. */
  22. public function find(iterable $bookIds): Collection
  23. {
  24. $ids = collect($bookIds)->map(fn ($id) => (int) $id)->unique()->values();
  25. if ($ids->isEmpty()) {
  26. return collect();
  27. }
  28. $titles = BookTitle::whereIn('sn', $ids)->get(['sn', 'book', 'paragraph']);
  29. if ($titles->isEmpty()) {
  30. return collect();
  31. }
  32. $heads = PaliText::query()
  33. ->where(function (Builder $q) use ($titles) {
  34. foreach ($titles as $title) {
  35. $q->orWhere(fn (Builder $q) => $q->where('book', $title->book)->where('paragraph', $title->paragraph));
  36. }
  37. })
  38. ->with('tagMaps.tags')
  39. ->get(['uid', 'book', 'paragraph', 'toc'])
  40. ->keyBy(fn (PaliText $t) => "{$t->book}-{$t->paragraph}");
  41. return $titles->mapWithKeys(function (BookTitle $title) use ($heads) {
  42. $head = $heads->get("{$title->book}-{$title->paragraph}");
  43. $tags = $head ? $head->tagMaps->map(fn ($map) => $map->tags?->name)->filter()->map('strval')->values()->all() : [];
  44. $layer = null;
  45. foreach (self::LAYER_TAGS as $tag => $value) {
  46. if (in_array($tag, $tags, true)) {
  47. $layer = $value;
  48. break;
  49. }
  50. }
  51. return [(int) $title->sn => [
  52. 'book_id' => (int) $title->sn,
  53. 'book' => (int) $title->book,
  54. 'para' => (int) $title->paragraph,
  55. 'title' => (string) ($head?->toc ?? ''),
  56. 'layer' => $layer,
  57. 'tags' => $tags,
  58. ]];
  59. });
  60. }
  61. }