G
G
Gordon Freeman2020-10-21 13:33:06
Laravel
Gordon Freeman, 2020-10-21 13:33:06

How to get common entities of related model (many-to-many)?

Hello! A little stuck, please help,
There is a post, there are tags, a many-to-many relationship;

The question
is how to get all and only those tags that are in all posts
- or get common post tags
- or, for example, make such a selection, all posts with tags (maximum links) and sort in descending order of the number of their links by posts
- or get the intersection of all sets of post tags

pseudocode

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MSAFT, 2020-10-21
@MSAFT

There is no need to do sortBy, get in the subquery.

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

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

Calculate quantity:
Tag::whereHas('posts')->count(); // 100

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question