最后一天检索了7个评论最多的帖子

时间:2017-05-27 09:35:10

标签: php laravel

我有评论的文章。我想根据7天内收到的评论在我的主页上发布5个热门项目。我试过这个:

$popularArticles = Article::published()
->whereHas('comments')
->withCount('comments')
->where('created_at', '>', \Carbon\Carbon::now()->subWeek())
->orderBy('comments_count', 'DESC')
->take(5)
->get();

但是使用这种方法,超过7天前创建的文章将被忽略"。我想要的是,过去7天的评论定义了文章是否受欢迎。

非常感谢

1 个答案:

答案 0 :(得分:1)

您需要按以下方式过滤计数的评论:

$popularArticles = Article::published()
    ->has('comments')
    ->withCount(['comments' => function ($q) {
        $q->where('created_at', '>', Carbon\Carbon::now()->subWeek());
    }])
    ->latest('comments_count')
    ->take(5)
    ->get();