diff --git a/extensions/tags/src/Handlers/TagMetadataUpdater.php b/extensions/tags/src/Handlers/TagMetadataUpdater.php index cbc75fd49..9bf280bfd 100755 --- a/extensions/tags/src/Handlers/TagMetadataUpdater.php +++ b/extensions/tags/src/Handlers/TagMetadataUpdater.php @@ -19,31 +19,41 @@ class TagMetadataUpdater { $tags = $event->discussion->tags(); - $this->updateTagCounts($tags, 1); + $this->updateTags($tags, 1, $event->discussion); } public function whenDiscussionWasTagged(DiscussionWasTagged $event) { $oldTags = Tag::whereIn('id', array_pluck($event->oldTags, 'id')); - $this->updateTagCounts($oldTags, -1); + $this->updateTags($oldTags, -1, $event->discussion); $newTags = $event->discussion->tags(); - $this->updateTagCounts($newTags, 1); + $this->updateTags($newTags, 1, $event->discussion); } public function whenDiscussionWasDeleted(DiscussionWasDeleted $event) { $tags = $event->discussion->tags(); - $this->updateTagCounts($tags, -1); + $this->updateTags($tags, -1, $event->discussion); $tags->detach(); } - protected function updateTagCounts($query, $delta) + protected function updateTags($query, $delta, $discussion) { - $query->update(['discussions_count' => app('db')->raw('discussions_count + '.$delta)]); + foreach ($query->get() as $tag) { + $tag->discussions_count += $delta; + + if ($delta > 0 && max($discussion->start_time, $discussion->last_time) > $tag->last_time) { + $tag->setLastDiscussion($discussion); + } elseif ($delta < 0 && $discussion->id == $tag->last_discussion_id) { + $tag->refreshLastDiscussion(); + } + + $tag->save(); + } } } diff --git a/extensions/tags/src/Tag.php b/extensions/tags/src/Tag.php index 5ba5fb3ac..9766ebbf8 100644 --- a/extensions/tags/src/Tag.php +++ b/extensions/tags/src/Tag.php @@ -1,6 +1,7 @@ belongsTo('Flarum\Core\Models\Discussion', 'last_discussion_id'); } + public function discussions() + { + return $this->belongsToMany('Flarum\Core\Models\Discussion', 'discussions_tags'); + } + + /** + * Refresh a tag's last discussion details. + * + * @return $this + */ + public function refreshLastDiscussion() + { + if ($lastDiscussion = $this->discussions()->orderBy('last_time', 'desc')->first()) { + $this->setLastDiscussion($lastDiscussion); + } + + return $this; + } + + /** + * Set the tag's last discussion details. + * + * @param \Flarum\Core\Models\Discussion $discussion + * @return $this + */ + public function setLastDiscussion(Discussion $discussion) + { + $this->last_time = $discussion->last_time; + $this->last_discussion_id = $discussion->id; + + return $this; + } + public static function getVisibleTo($user) { static $tags; - if (!$tags) { + if (! $tags) { $tags = static::all(); }