title: Laravel Eloquent hasMany Relation with Grouping and Sorting
body: <p>I am using Laravel 5.6 and would like to get a collection of featured articles published in the last 2 weeks sorted by the number of views over the last week.  Ideally using pagination on the model.</p>
  
  <p>DB:</p>
  
  <pre><code>author (id, name, ....)
  article (id, title, content, publish_date, ...)
  article_view (id, article_id, date, views)
  featured_article (id, article_id, created_at)
  </code></pre>
  
  <p>Models</p>
  
  
  
  <pre class="lang-php prettyprint-override"><code>class Author extends Model
  {
      protected $table = 'author';
      public function articles()
      {
          return $this-&gt;hasMany(Article::class,'id','author_id');
      }
  }
  
  class Article extends Model
  {
     protected $table = 'article';
     public function author()
     {
          return $this-&gt;hasOne(Author::class,'id','author_id');
     }
  }
  
  class FeaturedArticle extends Model
  { 
     protected $table = 'featured_article';
     static public function getFeaturedArticles($limit)
     {
       $articles = FeaturedArticles::where('created_at', '&gt;=', Carbon::now()-&gt;subDays(14))-&gt;with(['article.author','article.articleViews'])-&gt;paginate($limit);
     }
  }
  </code></pre>
  
  <p>Then in the Controller or Feature or Job</p>
  
  <pre class="lang-php prettyprint-override"><code>$featured_articles = FeaturedArticle::getFeaturedArticles(15);
  </code></pre>
  
  <p>This works fine, but the results aren't sorted yet. How to sort the paginated results by the sum of article_view.views over 7 days.  Is it possible?</p>