Replies: 1 comment 5 replies
-
Which version are you using? |
Beta Was this translation helpful? Give feedback.
5 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
hello every one.
I was wondering if the query for checking permission of a user can be improved.
when we use hasDirectPermission method it excecutes a query like this:
select
permissions.*,
model_has_permissions.
model_idas
pivot_model_id,
model_has_permissions.
permission_idas
pivot_permission_id,
model_has_permissions.
model_typeas
pivot_model_typefrom
permissionsinner join
model_has_permissionson
permissions.
id=
model_has_permissions.
permission_idwhere
model_has_permissions.
model_id= 1 and
model_has_permissions.
model_type= 'App\Models\User'
the code that runs this query and checks if user has permission is this:
return $this->permissions->contains('id', $permission->id);
in other words we load all of the user's permissions and perform the check in memory via a collection method.
what if we ran an exists query for that?
the code would be like this:
$this->permissions()->where('id', $permission->id)->exists();
and the query will be like this:
select exists(select * from
permissionsinner join
model_has_permissionson
permissions.
id=
model_has_permissions.
permission_idwhere
model_has_permissions.
model_id= 1 and
model_has_permissions.
model_type= 'App\Models\User' and
id= 10) as
exists``the benefit is that executed query will take less time because no data is being selected and only existence is checked and less models will be hydrated. for example if the user has 100 permissions in first case 100 model will be loaded from database but in second approach no model will be hydrated.
in my local enviornment 1000 permissions and a user that had 100 permissions first query took 2.16ms and second one will take 620us
if this is correct I'll be happy to make a pr for both permission and role
Beta Was this translation helpful? Give feedback.
All reactions