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

[2.x] perf(tags): prevent loading tag state if loaded previously #4009

Merged
merged 1 commit into from
Sep 20, 2024
Merged
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
13 changes: 11 additions & 2 deletions extensions/tags/src/Tag.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<int, Tag> $children
* @property-read Collection<int, Discussion> $discussions
Expand Down Expand Up @@ -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;
Expand Down
Loading