fix: tag state loaded for wrong user (#4009)

This commit is contained in:
Rafał Całka 2024-09-20 09:30:45 +02:00 committed by GitHub
parent aafc615d67
commit e1a77fd7c8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -43,7 +43,7 @@ use Illuminate\Database\Query\Builder as QueryBuilder;
* @property int $last_posted_user_id
* @property string $icon
*
* @property TagState $state
* @property TagState|null $state
* @property Tag|null $parent
* @property-read Collection<int, Tag> $children
* @property-read Collection<int, Discussion> $discussions
@ -166,7 +166,16 @@ class Tag extends AbstractModel
*/
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;