Hey guys I'm trying to develop a query which returns the trending articles from the database.
The trending articles are based on the most views over the last 24 hours. Here is the code so far:
$trending = Article::whereHas('view', function ($query) {
$query->where('created_at', '>=', Carbon::now()->subHours(24));
})
->with('view')
->orderBy('created_at', 'DESC')
->get();
return $trending;
}
The article model has the following relationship:
public function view()
{
return $this->hasMany('ArticleView', 'article_id');
}
The query works but I somehow need to also sort the articles by the view count. For example, the currently trending articles are displayed, but the artticles with the most view count are not ordered from first to last (obviously - they are ordered by created_at)
Help appreciated