假设我们有
id = 1
,posts
的表,有100个条目
如何计算每个用户的帖子,并向用户显示最多这样的帖子:
User 1: 59 posts
User 2: 20 posts
User 3: 15 posts
...
答案 0 :(得分:5)
有一个例子可能对你有帮助。
User::join('posts', function($builder){
$builder->on('posts.user_id', '=', 'user.id');
})
->select('users.*', 'COUNT(posts.*) as total_posts')
->groupBy('posts.id')
->orderBy('total_posts', 'ASC')
->get();
你可以试试这个例子可能对你有帮助。
答案 1 :(得分:0)
您可以执行与以下解决方案类似的操作:
$posts = DB::table('posts')
->select('posts.*', DB::raw('count(*) as total'))
->groupBy('user_id')
->get();
答案 2 :(得分:0)
我认为以下查询将起作用
Select count(id) as num_post from posts
group by (user_id)
order by (num_post) desc
此外,您可以将此加入users
表以获取用户数据
答案 3 :(得分:0)
使用原始SQL就像:
SELECT uid, COUNT(uid) postCount
FROM posts
GROUP BY uid HAVING postCoung >= (SELECT COUNT(1) FROM posts p2 GROUP BY p2.uid);
如果您想将其转换为Fluent:
DB::table(posts)
->SELECT("uid", DB::raw("COUNT(uid) postCount")
->groupBy("uid")
->havingRaw("postCount >= (SELECT COUNT(1) FROM posts p2 GROUP BY p2.uid)")->get();
在雄辩中,这只是使用适当模型的问题:
User::whereExists(function ($query) {
$query->table(posts)
->select("uid", DB::raw("COUNT(uid) postCount")
->where("users.id","=","uid")
->groupBy("uid")
->havingRaw("postCount >= (SELECT COUNT(1) FROM posts p2 GROUP BY p2.uid)")->get();
});