Angga Ari Wijaya
Angga Ari Wijaya

Reputation: 1811

Get all related many-to-many from all records instead from each record laravel

I have posts table related with tags table via post_tags. I want to get all tags from all user post. let's say a user have 3 posts, then I want to get all tags from 3 of them without loop in user post to get individual related tags of each post, it's like join + distinct but maybe there is method in Eloquent to make it easy. Thanks, let me know if my question is unclear or duplicate.

Upvotes: 1

Views: 33

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Use whereHas():

$tags = Tag::whereHas('posts', function($q) use($userId) {
    $q->where('user_id', $userId);
})->get();

Upvotes: 1

Related Questions