Jonathan Lightbringer
Jonathan Lightbringer

Reputation: 574

Filter laravel eloquent relationship

I have Groups, Users, GroupPositions, table.

Relationship:
Users belongsToMany Groups
Users belongsToMany GroupPositions
Group hasMany GroupPositions

//users
public function groupPositions() {
return $this->belongsToMany(
    'App\Models\GroupPositionView',
    'vw_group_members',
    'userId',
    'groupPositionId');
}

public function groups() {
return $this->belongsToMany(
    'App\Models\GroupView',
    'vw_group_members',
    'userId',
    'groupId');
}

I need to select a single group, with the members and their respective position in that particular group. A member can be part of different groups with DIFFERENT positions. He could be a leader in one group, or a manager in a different group.

Currently, I have this query:

$group = GroupView::where('tag', $tag)
->with(['user.groupPositions'])
->get();

It gives me ALL the positions of the member in all the group that he is a member of. I want to filter it to the specific group.

I also have this one:

$groupId = 1;
$group = GroupView::with(['users.groupPositions' => function($query) use($groupId) {
    $query->whereHas('group', function($query) use($groupId) {
        $query->where('groupId', $groupId);
    });
}])
->where('groupId', $groupId)
->firstOrFail();

This one works. However, the problem is that I need to get the group via tag. If I change all the groupId to tag, it does not work anymore. Probably because groupPositions and my vw_group_members does not have a tag column.

So my question is, is it possible to filter my query via tag?

Upvotes: 0

Views: 447

Answers (2)

Teun
Teun

Reputation: 926

If the GroupPositions are unique per group, you can switch around the with in the first query:

$group = GroupView::where('tag', $tag)
    ->with(['groupPositions.user'])
    ->get();

This gets the groupPositions of the group and the users belonging to them.

Upvotes: 8

Jonathan Lightbringer
Jonathan Lightbringer

Reputation: 574

 $group = GroupView::where('tag', $tag)->with(['groupPositions.user'])->get();

Credits to @Teun

Upvotes: 0

Related Questions