gpt4 book ai didi

php - Laravel orderBy whereHas

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:43:36 29 4
gpt4 key购买 nike

这个问题是关于:Laravel (5.3) Eloquent - Relationship issue , 请访问此 url 以获取更多信息。

我最终得到了以下脚本:

$genres = ['action', 'drama', 'romance'];

$similiarSeries = TheSeries::whereHas('TheGenres', function($q) use($genres) {
$q->whereIn('genre', $genres);
}, '>=', 1);

return $similiarSeries->take(10);

它的作用是:它从上述变量中​​检查至少具有 1 种类型的电影,并返回 10 部电影(如果存在)。

问题是他们的电影以困惑的顺序返回,相反,我更喜欢优先显示电影: Action 片、剧情片、浪漫片,然后返回那些只有 2 种类型的电影(比如:戏剧,浪漫或浪漫, Action )。然后只有一种流派。

这在 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

因此,如果我们搜索至少具有 ['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() 方法:

$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) 排序。

关于php - Laravel orderBy whereHas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41173698/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com