menu

arrow_back How do I get common entities of a linked model (many-to-many)?

by
1 vote
Hello! A little stuck, please help,
There is the post, there are the tags, the many-to-many connection;

Question
- How to get all and only those tags that are in all posts
- or get the common tags of the posts
- or, for example, make a sample of all posts with tags (maximum links) and sort them in descending order of the number of links
- or get the intersection of all sets of post tags

pseudocode
Tag::whereHas('posts', function($builder) {
$builder->count()
->sortBy('...')
->limit(5);
})
->get();

1 Answer

by
1 vote
There is no need to do sortBy, get in the nested query.

...get all and only those tags that are in all posts


Tag::whereHas('posts')->get()->sortBy('id'); // Коллекция


Count the number:
Tag::whereHas('posts')->count(); // 100

1 comment

Tag::whereHas('posts') condition of having a relation !== "tags, there are in all posts"