Skip to content

Commit

Permalink
fix(tags): load correct user tag state and prevent N+1 queries in `st…
Browse files Browse the repository at this point in the history
…ateFor` (#4008)

* fix: load tag state for correct user
* fix: prevent loading state if loaded previously
* fix(PHPStan): TagState can be null
  • Loading branch information
rafaucau committed Aug 10, 2024
1 parent 8415d22 commit b3366e4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
15 changes: 12 additions & 3 deletions extensions/tags/src/Tag.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<Tag> $children
* @property-read Collection<Discussion> $discussions
Expand Down Expand Up @@ -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;
Expand Down
8 changes: 7 additions & 1 deletion extensions/tags/src/TagRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}

Expand Down

0 comments on commit b3366e4

Please sign in to comment.