diff --git a/extensions/tags/src/Tag.php b/extensions/tags/src/Tag.php index 2bcbab5c15..3b80356ecd 100644 --- a/extensions/tags/src/Tag.php +++ b/extensions/tags/src/Tag.php @@ -36,7 +36,7 @@ * @property int $last_posted_user_id * @property string $icon * - * @property TagState $state + * @property TagState|null $state * @property Tag|null $parent * @property-read Collection $children * @property-read Collection $discussions @@ -163,9 +163,18 @@ public function state() * @param User $user * @return TagState */ - public function stateFor(User $user) + public function stateFor(User $user): TagState { - $state = $this->state()->where('user_id', $user->id)->first(); + // Use the loaded state if the relation is loaded, and either: + // 1. The state is null, or + // 2. The state belongs to the given user. + // This ensures that if a non-null state is loaded, it belongs to the correct user. + // If these conditions are not met, we query the database for the user's state. + if ($this->relationLoaded('state') && (! $this->state || $this->state->user_id === $user->id)) { + $state = $this->state; + } else { + $state = $this->state()->where('user_id', $user->id)->first(); + } if (! $state) { $state = new TagState; diff --git a/extensions/tags/src/TagRepository.php b/extensions/tags/src/TagRepository.php index 8ea1b683b1..c1f08571c8 100644 --- a/extensions/tags/src/TagRepository.php +++ b/extensions/tags/src/TagRepository.php @@ -57,7 +57,13 @@ public function getAuthorizedRelations($relations, User $actor): array $query->whereVisibleTo($actor); }; } else { - $relationsArray[] = $relation; + if ($relation === 'state') { + $relationsArray['state'] = function ($query) use ($actor) { + $query->where('user_id', $actor->id); + }; + } else { + $relationsArray[] = $relation; + } } }