首页 > 解决方案 > 查找在过去 24 小时内创建的帖子最多的用户,laravel Eloquent

问题描述

如何在 laravel 中找到过去 24 小时内创建的帖子最高的用户?按帖子数量降序排列。

标签: laraveleloquent

解决方案


如果我没记错的话,您是在询问在过去 24 小时内创建的帖子数量最多的用户。

为此,请执行以下操作:

$users = User::withCount(['posts' => function ($query) {
            $query->where('created_at', '>=', carbon()->now()->subDay());
        }])->orderBy('posts_count', 'DESC')
            ->get();

正如文档所述,您可以向查询添加约束。

计数相关模型

如果您想在不实际加载关系的情况下计算关系结果的数量,您可以使用该 withCount方法,该方法将{relation}_count在您的结果模型上放置一列。例如:

$posts = App\Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;
}

您可以为多个关系添加“计数”,并为查询添加约束:

$posts = Post::withCount(['votes', 'comments' => function ($query) {
    $query->where('content', 'like', 'foo%');
}])->get();

echo $posts[0]->votes_count;
echo $posts[0]->comments_count;

推荐阅读