此问题与以下内容有关:Laravel(5.3)Eloquent - 关系问题,请访问此网址以获取更多信息.
我最终得到了以下脚本:
$genres = ['action', 'drama', 'romance'];
$similiarSeries = TheSeries::whereHas('TheGenres', function($q) use($genres) {
$q->whereIn('genre', $genres);
}, '>=', 1);
return $similiarSeries->take(10);
Run Code Online (Sandbox Code Playgroud)
它的作用是:它检查上面变量至少有1个类型的电影,并返回10部电影(如果存在).
问题在于他们的电影是以混乱的顺序返回的,相反,如果他们会优先播放动作,戏剧,浪漫,然后返回只有2种类型的电影(如:戏剧,浪漫或浪漫,行动).然后只有1种类型.
这是否可能在laravel?
这是电影及其类型的示例列表:
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
Run Code Online (Sandbox Code Playgroud)
因此,如果我们搜索的电影至少包含['动作','戏剧','浪漫'],
我期待以下内容被退回:
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)
Run Code Online (Sandbox Code Playgroud)
好的,明白了。
从 Laravel 5.2.41 开始,您可以使用withCount()如下方法:
$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);
Run Code Online (Sandbox Code Playgroud)
这将按匹配的流派数量(描述)排序。
| 归档时间: |
|
| 查看次数: |
1040 次 |
| 最近记录: |