From e1a77fd7c88540aa2247b752ced597f5ca981d8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Ca=C5=82ka?= <25438601+rafaucau@users.noreply.github.com> Date: Fri, 20 Sep 2024 09:30:45 +0200 Subject: [PATCH] fix: tag state loaded for wrong user (#4009) --- extensions/tags/src/Tag.php | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/extensions/tags/src/Tag.php b/extensions/tags/src/Tag.php index e647c118ba..73283d2076 100644 --- a/extensions/tags/src/Tag.php +++ b/extensions/tags/src/Tag.php @@ -43,7 +43,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 @@ -166,7 +166,16 @@ public function state(): HasOne */ 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;