2
0

ProgressChapterService.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. $tagCount = count($this->tags);
  41. $chapters = ProgressChapter::where('progress', '>', $this->minProgress)
  42. ->whereHas('channel', function ($query) {
  43. $query->where('owner_uid', $this->channelOwnerId);
  44. })->whereHas('tags', function ($query) {
  45. $query->whereIn('name', $this->tags);
  46. }, '=', $tagCount)->get();
  47. return $chapters;
  48. }
  49. public function getTags()
  50. {
  51. $tagCount = count($this->tags);
  52. $chapters = ProgressChapter::where('progress', '>', $this->minProgress)
  53. ->whereHas('channel', function ($query) {
  54. $query->where('owner_uid', $this->channelOwnerId);
  55. })->whereHas('tags', function ($query) {
  56. $query->whereIn('name', $this->tags);
  57. }, '=', $tagCount)->select('uid')->get();
  58. $tagMaps = TagMap::with('tags')->whereIn('anchor_id', $chapters)
  59. ->get();
  60. $tags = [];
  61. foreach ($tagMaps as $key => $value) {
  62. if (isset($tags[$value->tag_id])) {
  63. $tags[$value->tag_id]['count']++;
  64. } else {
  65. $tags[$value->tag_id] = [
  66. 'tag' => $value->tags,
  67. 'count' => 1
  68. ];
  69. }
  70. }
  71. $tagsValue = array_values($tags);
  72. // 按 count 降序排序
  73. usort($tagsValue, function ($a, $b) {
  74. return $b['count'] <=> $a['count']; // PHP 7+ 使用 spaceship 运算符
  75. });
  76. return $tagsValue;
  77. }
  78. }