制定一个趋势查询 - Laravel Eloquent

Jos*_*osh 2 sorting trending laravel eloquent

嘿家伙我正在尝试开发一个从数据库中返回趋势文章的查询.

热门文章基于过去24小时内的大多数观点.这是迄今为止的代码:

$trending = Article::whereHas('view', function ($query) {
   $query->where('created_at', '>=', Carbon::now()->subHours(24));
})
->with('view')
->orderBy('created_at', 'DESC')
->get();

return $trending;
}
Run Code Online (Sandbox Code Playgroud)

文章模型具有以下关系:

public function view()
{
    return $this->hasMany('ArticleView', 'article_id');
}
Run Code Online (Sandbox Code Playgroud)

该查询有效,但我还需要按视图计数对文章进行排序.例如,显示当前趋势文章,但具有最多视图计数的artticles不是从头到尾排序(显然 - 它们按created_at排序)

帮助赞赏

Cpt*_*xon 5

你可以采取几种方法,

  1. 比如@Oli说,在你的表中添加一个列,你保存最近24小时的number_views,数据库中的触发器将使它保持最新.就像每次有视图一样,它会重新调整场地.

  2. 添加一个附加的24h_views_count运行您的查询,然后在代码中排序

    protected $appends= ['24h_views_count']
    
    public get24hViewsCountAttribute(){
    return $this->view()->where('created_at', '>=', Carbon::now()->subHours(24))->count();
    }
    
    //and after you get the result from trending just sort the collection via that property.
    $trending->sortByDesc('24h_views_count');//this will sort it from highest to lowest 
    
    Run Code Online (Sandbox Code Playgroud)
  3. 第三个选项是使用SQL,它看起来像它在这里看起来:https://laracasts.com/discuss/channels/general-discussion/eloquent-order-by-related-table