Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[1.x] fix(tags): load correct user tag state and prevent N+1 queries in stateFor #4008

Merged
merged 3 commits into from
Aug 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading