mughalseohub's avatar

understanding laravel (Solved)

I have a user table and a role table. I made a pivot table with role_id and user_id with foreign key with delete on cascade refrencing to role and user table. The user and role model has a belongstomany relationship .i want to get the users with the employee role. by writing the code $a = Role::where('role','employee')->first()->User; i get the users with employee role but i don't understand how Laravel got the role matched with the pivot table and returned the users with that role. Can anyone please explain this?

0 likes
6 replies
tykus's avatar

You could have achieved this with a single query instead of the two that your query would need:

$employees = User::query()
    ->whereHas('roles', fn ($builder) => $builder->where('role', 'employee'))
    ->get(); 

This results in a single SQL query like this which joins the pivot and roles tables to constrain the results

select * from `users` where exists (select * from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `users`.`id` = `role_user`.`user_id` and `role` = employee));
1 like
tykus's avatar

@mughalseohub yes, because that is what you asked for:

i want to get the users with the employee role

If you also need the Role record, then two queries are needed.

1 like

Please or to participate in this conversation.