Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.8 - How sort (orderBy) multiple relationship

I am trying to sort the serials by video views.

Relations: The Serial has a hasMany relationship to series. The Series has a hasMany relationship to episodes. The Episodes has a hasOne relationship to video. The Video has a hasMany relationship to viewcounts.

<?php
//sort method:
public function mostPopular()
    {

        $serials = Serial::with(['series.episodes.video' => function ($query) {
            $query->withCount(['videoViews' => function($query) {
            }])->orderBy('video_views_count', 'desc');
        }])->get();

        return $serials;
}

//Serial model:
public function series()
{
   return $this->hasMany(Series::class);
}


//Series model:
public function episodes()
{
   return $this->hasMany(Episode::class);
}

public function serial()
{
   return $this->belongsTo(Serial::class);
}

//Episode model:
public function video()
{
   return $this->hasOne(Video::class);
}

public function series()
{
   return $this->belongsTo(Series::class);
}

//Video model:
public function videoViews()
{
   return $this->hasMany(VideoView::class);
}

public function episode()
{
   return $this->belongsTo(Episode::class);
}


?>

I expect the sorted serials by video views (series.episodes.video.videoViews), but the actual output is not sorted.

Laravel 5.8 PHP 7

like image 243
andrej_14 Avatar asked Jan 23 '26 12:01

andrej_14


1 Answers

This is a silly one actually but I've learnt that multiple ->sortBy on collections actually are possible with no workarounds. It's just that you need to reverse the order of them. So, to sort a catalogue of artists with their album titles this would be the solution...

Instead of :

$collection->sortBy('artist')->sortBy('title');

Do this :

$collection->sortBy('title')->sortBy('artist');
like image 185
anoraq Avatar answered Jan 26 '26 04:01

anoraq