filaret's avatar

How to order and sort data by relations?

Currently I have this code in controller and it works. I am grabbing all urls including category (url can have only 1 category) and only latest 2 analytics row for each url. How can I get data sortable by Category name (asc and desc) and also by Analytics quality column (asc and desc)? Is it possible to do it cleanly with a query or do I have to loop through all this data after being fetched and do some dirty work with sorting? In that case pagination (which currently I have omitted) will also become problem...

Url Controller

 $urls = URL::
        with('category')
        ->with('analytics')->get()->map(function($urls) {
            $urls->analytics = $urls->analytics->take(2);
            return $urls;
        });

Url Model

class Url extends Model
{

    protected $table = 'urls';

    public function analytics()
    {
        return $this->hasMany('App\Analytic');
    }

    public function category()
    {
        return $this->belongsTo('App\Category');
    }

}

Urls table

    id | url | category_id

Category table

id | category

Analytics table

id | quality | url_id
0 likes
0 replies

Please or to participate in this conversation.