Skip to content

Commit

Permalink
Bugfix: Solved N+1 problem in User isDeletable()
Browse files Browse the repository at this point in the history
  • Loading branch information
kreaweb.be committed May 25, 2024
1 parent 7368e3a commit 19e1f93
Show file tree
Hide file tree
Showing 3 changed files with 230 additions and 36 deletions.
2 changes: 1 addition & 1 deletion app/Models/Team.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ protected function casts(): array
/* -------------------------------------------------------------------------------------------- */
public function isDeletable(): bool
{
return count($this->persons) == 0 and count($this->couples) == 0 and count($this->users) == 0;
return $this->persons->count() == 0 and $this->couples->count() and $this->users->count() == 0;
}

/* -------------------------------------------------------------------------------------------- */
Expand Down
14 changes: 8 additions & 6 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,15 @@ public function teamsStatistics()

public function isDeletable(): bool
{
foreach ($this->ownedTeams as $team) {
if (! $team->isDeletable()) {
return false;
}
}
$count = DB::select('
SELECT
SUM((SELECT COUNT(*) FROM `users` INNER JOIN `team_user` ON `users`.`id` = `team_user`.`user_id` WHERE `teams`.`id` = `team_user`.`team_id` AND `users`.`deleted_at` IS NULL)) +
SUM((SELECT COUNT(*) FROM `people` WHERE `teams`.`id` = `people`.`team_id` AND `people`.`deleted_at` IS NULL)) +
SUM((SELECT COUNT(*) FROM `couples` WHERE `teams`.`id` = `couples`.`team_id`)) AS `items_count`
FROM `teams` WHERE `user_id` = ' . $this->id . ';
');

return true;
return (int) reset($count[0]) == 0;
}

/* -------------------------------------------------------------------------------------------- */
Expand Down

0 comments on commit 19e1f93

Please sign in to comment.