Просмотр файла app/Models/Forum.php

Размер файла: 2.68Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Models;
  6.  
  7. use Illuminate\Database\Eloquent\Collection;
  8. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  9. use Illuminate\Database\Eloquent\Relations\HasMany;
  10.  
  11. /**
  12. * Class Forum
  13. *
  14. * @property int id
  15. * @property int sort
  16. * @property int parent_id
  17. * @property string title
  18. * @property string description
  19. * @property int count_topics
  20. * @property int count_posts
  21. * @property int last_topic_id
  22. * @property int closed
  23. * @property Forum parent
  24. * @property Collection children
  25. * @property Topic lastTopic
  26. */
  27. class Forum extends BaseModel
  28. {
  29. /**
  30. * Indicates if the model should be timestamped.
  31. *
  32. * @var bool
  33. */
  34. public $timestamps = false;
  35.  
  36. /**
  37. * The attributes that aren't mass assignable.
  38. *
  39. * @var array
  40. */
  41. protected $guarded = [];
  42.  
  43. /**
  44. * Возвращает связь родительского форума
  45. *
  46. * @return BelongsTo
  47. */
  48. public function parent(): BelongsTo
  49. {
  50. return $this->belongsTo(self::class, 'parent_id')->withDefault();
  51. }
  52.  
  53. /**
  54. * Возвращает связь подкатегорий форума
  55. *
  56. * @return HasMany
  57. */
  58. public function children(): HasMany
  59. {
  60. return $this->hasMany(self::class, 'parent_id')->orderBy('sort');
  61. }
  62.  
  63. /**
  64. * Возвращает связь последней темы
  65. *
  66. * @return BelongsTo
  67. */
  68. public function lastTopic(): BelongsTo
  69. {
  70. return $this->belongsTo(Topic::class, 'last_topic_id')->withDefault();
  71. }
  72.  
  73. /**
  74. * Пересчет раздела
  75. *
  76. * @return void
  77. */
  78. public function restatement(): void
  79. {
  80. $lastTopic = Topic::query()
  81. ->where('forum_id', $this->id)
  82. ->orderByDesc('updated_at')
  83. ->first();
  84.  
  85. $topic = Topic::query()
  86. ->selectRaw('count(*) as count_topics, sum(count_posts) as count_posts')
  87. ->where('forum_id', $this->id)
  88. ->first();
  89.  
  90. $this->update([
  91. 'count_topics' => $topic ? (int) $topic->count_topics : 0,
  92. 'count_posts' => $topic ? (int) $topic->count_posts : 0,
  93. 'last_topic_id' => $lastTopic ? $lastTopic->id : 0,
  94. ]);
  95.  
  96. if ($this->parent->id) {
  97. $forumIds = $this->parent->children->pluck('id')->all();
  98. $forumIds[] = $this->parent->id;
  99.  
  100. $lastTopic = Topic::query()
  101. ->whereIn('forum_id', $forumIds)
  102. ->orderByDesc('updated_at')
  103. ->first();
  104.  
  105. $this->parent()->update([
  106. 'last_topic_id' => $lastTopic ? $lastTopic->id : 0
  107. ]);
  108. }
  109. }
  110. }