laravel - 查找在过去 24 小时内创建的帖子最多的用户,laravel Eloquent
问题描述
如何在 laravel 中找到过去 24 小时内创建的帖子最高的用户?按帖子数量降序排列。
解决方案
如果我没记错的话,您是在询问在过去 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;
推荐阅读
- python - 如何在 Python 中对多个整数进行排序而不使它们成为数组或列表
- php - 如何在选择表单上自动提交但选项不会再次恢复默认值?
- angular - 无法读取未定义的属性“valueChanges”
- php - 使用Mysql和PHP从多个表中查询数据
- centos - 如何在 Centos OS 中恢复已删除的 yum.repos.d?
- nfc - NFC会员卡提交后会发生什么?
- mysql - “LIKE %%”是否与“LIKE %”相同?
- android - 带有裸 React-Native 的 Expo Video,不适用于 Android 5.1 及更低版本
- javascript - 有没有办法使用循环在 JS 警报框中打印多行?
- django - Google App Engine:部署前端和后端配置(Nuxt + Django)