I would give this a watch: https://laracasts.com/lessons/users-and-roles. While its not referred to as a "group" its essentially the same technique. I recently used the same process on an app with L5.
L5 Eloquent Query Question - Roles / Groups
Hey all @JarekTkaczyk
I hope you all are having a relaxing weekend.
This is a basic question, but would appreciate your help. I have 2 models / tables. One is groups and the other group members. What is the optimal way to query the models. Is it:
- as my example below
- through a relationship
- or MySQL join or something
- pull a subset into an array and have PHP array methods do the iteration
Scenario:
- Group model / groups table and the query will result in 20 - 50 results
- GroupMember / group_members table and for each of the group results another 50 members
As it a role type and such this query will be called on every user permission checks in different collaboration workspaces i.e. I'm scenario I'm looking for the optimal approach as the user could click on one workspace then the next and each will need to check the users role/ membership against the permission groups to get their membership.
public function getGroupMembership($company = null, $user = null)
{
$members = array();
// look for all groups that are equal to company id
// let's assume the result is 20
$groups = Group::where('company_id', '=', $company)->get();
foreach($groups as $group)
{
$members[] = $this->groupMember
->where('user_id', '=', $user->id)
->where('group_id','=', $group->id)
->get();
}
return $members;
}
many thanks
@nolros You are executing multiple queries in this loop. You don't need that. Also you get an array of collections, doesn't look convenient.
public function getRoles(WorkSpace $workSpace, User $user)
{
// get all security groups for this workspace
$groupsIds = EloquentSecurityGroup::where('space_id', '=', $workSpace->id)->lists('id');
$userId = $user->uuid;
return EloquentSecurityGroupMember::whereHas('group', function ($q) use ($groupsIds, $userId) {
$q->whereIn('security_group_id', $groupsIds)
->where('user_id', $userId);
})->get();
}
Please or to participate in this conversation.