我的网页上有Top Shows
的列表,这些列表是根据show_id
分组剧集生成的,并按view
对其进行排序。我急切地在查询中加载Show
,如下所示:
public function getPopularShows($amount = null)
{
if (!$amount) {
return $this->episode->groupBy('show_id')->orderBy('views', 'desc')->with('show')->get();
}
return $this->episode->groupBy('show_id')->orderBy('views', 'desc')->with('show')->get()->take($amount);
}
然而,这显然会返回episodes
的集合,我想要一个shows
的集合。有这样做的聪明方法吗?
我现在能想到的唯一方法就是做一个array_map
并用剧本换掉这一集。
答案 0 :(得分:0)
我不知道我是否理解你想要达到的目标,但也许这就是你需要的东西
public function getPopularShows($amount = null)
{
return Show::whereIn('id', function($q) use ($amount) {
$q = $q->selectRaw('show_id')->from('episodes')->orderBy('views','DESC');
if ($amount) {
$q = $q->take($amount);
}
$q->get();
})->get();
}