user1970557
user1970557

Reputation: 515

Eloquent many-to-many relationships

I have 3 tables:

groups:
id, name

group_members:
id, group_id, user_id

users:
id

Now, what I'm looking to do, is to get all of the groups (just the groups), that have members associated with them so, for instance i have the following:

groups
1, test
2, test-1
3, test-2

group_members
1, 1, 1
2, 1, 2
3, 3, 1

users
1
2

If I want to get all groups that user with id = 1 belongs to, it should return:

groups
1, test
3, test-2

Is there a way in eloquent that i can just return the groups (in a collection)

Thanks

Upvotes: 1

Views: 37

Answers (2)

user1970557
user1970557

Reputation: 515

Group::whereHas('members', function($q) use($userId) {
    $q->where('user_id', $userId);
})->get();

This seems to work. I had to add some of the belongsTo etc relationships in my models

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

You can use whereHas():

Group::whereHas('users', function($q) use($userId) {
    $q->where('id', $userId);
})->get();

Or:

User::find($userId)->groups()->get();

Upvotes: 1

Related Questions