ProgressChapterService.php 2.3 KB

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