简体   繁体   中英

Get top rows from relation

I have 2 models: Video , Country and want to retrieve the top 5 videos for each country ordered by number of views, and want to do that using the video model not the country model so i shall start with

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

So the code shall return videos from the top 5 for reach country

and will be appreciate if the solution that starts with County::with('videos') is given

This should help, it return videos without iterating any loops.

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

You must need this loop to get videos

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

foreach ($countries as $country) {
    $top_5_videos = $country->videos->take(5);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM