Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel orderBy whereHas

Tags:

php

laravel

This question is related to: Laravel (5.3) Eloquent - Relationship issue, please access 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 it does is: It checks for movies which has at least 1 genre from above variable, and returns 10 movies (if exist).

The problem is that they movies are being returned in a chaotic order, instead I would preffer if they would be displayed giving priority to the movies which are: action, drama, romance and then return those movies with only 2 genres (like: drama, romance or romance, action). and then only 1 genre.

Is this possible in laravel?

UPDATE

This is an example list of movies 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 search movies which have at least one of ['action','drama','romance'],

I am expecting 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)
like image 595
Coder Avatar asked Oct 29 '22 15:10

Coder


1 Answers

Ok, got you.

As of Laravel 5.2.41 you can use withCount() method like this:

$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 order by matched genres count (desc).

like image 154
Artur Subotkevič Avatar answered Nov 15 '22 05:11

Artur Subotkevič