Yunis Hawwash
Yunis Hawwash

Reputation: 98

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

Upvotes: 0

Views: 76

Answers (2)

Vishal Ribdiya
Vishal Ribdiya

Reputation: 880

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;
}

Upvotes: 2

Ravisha Hesh
Ravisha Hesh

Reputation: 1504

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

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

Upvotes: 0

Related Questions