【问题标题】:Laravel orderBy whereHasLaravel orderBy whereHas
【发布时间】:2016-12-16 18:24:02
【问题描述】:

此问题与:Laravel (5.3) Eloquent - Relationship issue有关,请访问此网址了解更多信息。

我最终得到了以下脚本:

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

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

return $similiarSeries->take(10);

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

问题是他们的电影以混乱的顺序被退回,相反,如果它们优先显示以下电影,我会更喜欢:动作、戏剧、浪漫,然后退回那些只有 2 种类型的电影(比如:戏剧,浪漫或浪漫,动作)。然后只有一种类型。

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

【问题讨论】:

  • 请尝试再举一个例子。带有真实的电影名称和流派名称。你有什么,你需要退回什么。
  • #ArturSubotkevic 刚刚更新了问题。
  • 也有 0 个流派?什么?
  • @ArturSubotkevic 是的,如果电影少于 10 部,则需要填补空间。

标签: php laravel


【解决方案1】:

好的,知道了。

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

【讨论】:

  • 我刚查了一下,有一个问题,这个统计的是一个特定系列的流派数量实际上并不是我需要的。
  • 等等...那么您需要多少计数? :D
  • 我需要它按属于给定数组的流派进行排序。
  • 再看我的例子,你理解错了。
  • 您的示例将首先显示具有 5 种类型的电影,而不是我需要显示具有提供数组中最大类型数量的电影。
猜你喜欢
  • 2015-07-29
  • 2022-01-27
  • 2017-09-21
  • 1970-01-01
  • 2018-09-18
  • 2021-08-23
  • 1970-01-01
  • 2019-12-28
  • 2023-03-07
相关资源
最近更新 更多