Laravel orderBy whereHas

This question is related to: Laravel (5.3) Eloquent - relationship question , please refer to this URL for more information.

I ended up with the following script:

$genres = ['action', 'drama', 'romance']; $similiarSeries = TheSeries::whereHas('TheGenres', function($q) use($genres) { $q->whereIn('genre', $genres); }, '>=', 1); return $similiarSeries->take(10); 

What he does: he checks films that have at least 1 genre from the above, and returns 10 films (if they exist).

The problem is that they are shot in a chaotic manner, instead I would prefer them to be shown, giving priority to films that are: action, drama, romance, and then return these films with only two genres (for example:: drama , romance or romance, action). and then only 1 genre.

Is this possible in laravel?

UPDATE

This is an example of a list of films and their genres:

 Zootopia: Action, Animation, Drama Toy Story: Action, Drama, Romance Kung Fu Panda: Action, Animation, Fantasy Avatar: Action, Drama, Romance Titanic: Action, Drama, Romance Avengers: Fantasy, Drama, Fiction Batman: Adventure 

So, if we are looking for films that have at least one of ['action', 'drama', 'romance'],

I expect the following to be returned:

 Toy Story (Action, Drama, Romance) (3) Avatar (Action, Drama, Romance) (3) Titanic (Action, Drama, Romance) (3) Zootopia (Action, Drama) (2) Kung Fu Panda (Action) (1) Avengers (Drama) (1) Batman (0) 
+5
source share
1 answer

Ok, got it.

As in Laravel 5.2.41, you can use the withCount() method as follows:

 $similiarSeries = TheSeries::whereHas('TheGenres', function($q) use($genres) { $q->whereIn('genre', $genres); })->withCount(['TheGenres' => function ($query) use ($genres) { $query->whereIn('genre', $genres); }])->orderBy('TheGenres_count', 'desc'); return $similiarSeries->take(10); 

This will be sorted by the same number of genres (desc).

+2
source

Source: https://habr.com/ru/post/1261355/


All Articles