ProgressChapterService.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace App\Services;
  3. use App\Models\ProgressChapter;
  4. use App\Models\TagMap;
  5. class ProgressChapterService
  6. {
  7. protected $tags = null;
  8. protected $channelId = null;
  9. protected $channelType = null;
  10. protected $channelOwnerId = null;
  11. protected $minProgress = 0.01;
  12. public function setProgress($progress)
  13. {
  14. $this->minProgress = $progress;
  15. return $this;
  16. }
  17. public function setChannel($channelId)
  18. {
  19. $this->channelId = $channelId;
  20. return $this;
  21. }
  22. public function setChannelType($channelType)
  23. {
  24. $this->channelType = $channelType;
  25. return $this;
  26. }
  27. public function setChannelOwnerId($channelOwnerId)
  28. {
  29. $this->channelOwnerId = $channelOwnerId;
  30. return $this;
  31. }
  32. public function setTags($tags)
  33. {
  34. $this->tags = $tags;
  35. return $this;
  36. }
  37. public function get()
  38. {
  39. $tagCount = count($this->tags);
  40. $chapters = ProgressChapter::where('progress', '>', $this->minProgress)
  41. ->whereHas('channel', function ($query) {
  42. $query->where('owner_uid', $this->channelOwnerId);
  43. })->whereHas('tags', function ($query) {
  44. $query->whereIn('name', $this->tags);
  45. }, '=', $tagCount)->get();
  46. return $chapters;
  47. }
  48. public function getTags()
  49. {
  50. $tagCount = count($this->tags);
  51. $chapters = ProgressChapter::where('progress', '>', $this->minProgress)
  52. ->whereHas('channel', function ($query) {
  53. $query->where('owner_uid', $this->channelOwnerId);
  54. })->whereHas('tags', function ($query) {
  55. $query->whereIn('name', $this->tags);
  56. }, '=', $tagCount)->select('uid')->get();
  57. $tagMaps = TagMap::with('tags')->whereIn('anchor_id', $chapters)
  58. ->get();
  59. $tags = [];
  60. foreach ($tagMaps as $key => $value) {
  61. if (isset($tags[$value->tag_id])) {
  62. $tags[$value->tag_id]['count']++;
  63. } else {
  64. $tags[$value->tag_id] = [
  65. 'tag' => $value->tags,
  66. 'count' => 1,
  67. ];
  68. }
  69. }
  70. $tagsValue = array_values($tags);
  71. // 按 count 降序排序
  72. usort($tagsValue, function ($a, $b) {
  73. return $b['count'] <=> $a['count']; // PHP 7+ 使用 spaceship 运算符
  74. });
  75. return $tagsValue;
  76. }
  77. }