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

fixed: roles n+1 queries #171

Merged
merged 3 commits into from
Feb 17, 2022
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
35 changes: 30 additions & 5 deletions src/Traits/HasRoleAndPermission.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,22 @@ public function roles()
*/
public function getRoles()
{
return (!$this->roles) ? $this->roles = $this->roles()->get() : $this->roles;
if (!$this->roles) {
if (method_exists($this, 'loadMissing')) {
$this->loadMissing('roles');
} else {
if (!array_key_exists('roles', $this->relations)) {
$this->load('roles');
}
}
if (method_exists($this, 'getRelation')) {
$this->roles = $this->getRelation('roles');
} else {
$this->roles = $this->relations['roles'];
}
}

return $this->roles;
}

/**
Expand Down Expand Up @@ -130,7 +145,7 @@ public function attachRole($role)
if ($this->getRoles()->contains($role)) {
return true;
}
$this->roles = null;
$this->resetRoles();

return $this->roles()->attach($role);
}
Expand All @@ -144,7 +159,7 @@ public function attachRole($role)
*/
public function detachRole($role)
{
$this->roles = null;
$this->resetRoles();

return $this->roles()->detach($role);
}
Expand All @@ -156,7 +171,7 @@ public function detachRole($role)
*/
public function detachAllRoles()
{
$this->roles = null;
$this->resetRoles();

return $this->roles()->detach();
}
Expand All @@ -170,7 +185,7 @@ public function detachAllRoles()
*/
public function syncRoles($roles)
{
$this->roles = null;
$this->resetRoles();

return $this->roles()->sync($roles);
}
Expand Down Expand Up @@ -442,6 +457,16 @@ private function getArrayFrom($argument)
return (!is_array($argument)) ? preg_split('/ ?[,|] ?/', $argument) : $argument;
}

protected function resetRoles()
{
$this->roles = null;
if (method_exists($this, 'unsetRelation')) {
$this->unsetRelation('roles');
} else {
unset($this->relations['roles']);
}
}

public function callMagic($method, $parameters)
{
if (starts_with($method, 'is')) {
Expand Down