Laravel订单在哪里 [英] Laravel orderBy whereHas

查看:124
本文介绍了Laravel订单在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与以下问题有关: Laravel(5.3)口才很高-关系问题,请访问此网址以获取更多信息.

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);

它的作用是:它检查上述变量中​​至少具有1种类型的电影,并返回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.

laravel有可能吗?

Is this possible in laravel?

这是电影及其类型的示例列表:

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'],

我希望返回以下内容:

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)

推荐答案

好,知道了.

从Laravel 5.2.41开始,您可以使用如下的withCount()方法:

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);

这将根据匹配的流派计数(desc)进行排序.

This will order by matched genres count (desc).

这篇关于Laravel订单在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆