从关系中获取顶行

问题描述 投票:0回答:2

我有2个型号:VideoCountry,想要按照视图数量排序检索每个国家的前5个视频,并希望使用视频模型而不是国家模型这样做,所以我将从

$videos = Video::with('user')->orderBy('views', 'desc')->get();

因此,代码应返回前5个国家/地区的视频

如果给出以County::with('videos')开头的解决方案,我们将不胜感激

laravel laravel-5 eloquent laravel-5.2
2个回答
1
投票

这应该有帮助,它返回视频而不迭代任何循环。

 $countries = Country::with(['videos' => function($query) {
     $query->orderBy('views', 'desc')->take(5);
 }])->get();

你必须需要这个循环来获取视频

$topVideos = [];
foreach ($countries as $country) {
   $topVideos[] = $country->videos;
}

0
投票
$countries = Country::with(['videos' => function($query){
        $query->orderBy('views', 'desc');
    }])
    ->get();

foreach ($countries as $country) {
    $top_5_videos = $country->videos->take(5);
}
© www.soinside.com 2019 - 2024. All rights reserved.