2

データベースからトレンドの記事を返すクエリを開発しようとしています。

トレンド記事は、過去 24 時間で最も多く閲覧された記事に基づいています。これまでのコードは次のとおりです。

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

return $trending;
}

記事モデルには次の関係があります。

public function view()
{
    return $this->hasMany('ArticleView', 'article_id');
}

クエリは機能しますが、ビュー数で記事を並べ替える必要があります。たとえば、現在トレンドになっている記事が表示されますが、閲覧回数が最も多い記事は最初から最後まで並べられていません (明らかに、created_at によって並べ替えられています)。

助けていただければ幸いです

4

2 に答える 2

5

いくつかのアプローチがあり、

  1. @Oliが言ったように、過去24時間のnumber_viewsを保存するテーブルに列を追加すると、DBのトリガーが最新の状態に保ちます。ビューがあるたびに、フィールドが再計算されます。

  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 
    
  3. 3 番目のオプションは SQL を使用することで、次のようになります: https://laracasts.com/discuss/channels/general-discussion/eloquent-order-by-related-table

于 2016-04-14T06:41:58.757 に答える