我一直在编写 Eloquent 查询来查找我的帖子获得最多选票时遇到问题。我有一个投票表和一个帖子表。 votes 表有一个 id 列、一个 post_id 列、一个 user_id 列和一个 vote 列。如果有人为帖子投票,则投票列的值设置为 1。如果有人对帖子投反对票,则投票列设置为 0。我可以使用以下查询找到一个帖子的投票数量:
Vote::where('post_id','=', $post->id)->where('vote','=',1)->count()
我如何改进此查询以找到得票最多的帖子?我试过想出一种方法,但我似乎做不到。非常感谢。
最佳答案
就做....
DB::table('votes')->orderBy(DB::raw('sum(\'vote\')'))
->groupBy('post_id')->get();
这将按 SUM 排序您的选票
关于php - 编写 Eloquent 查询以查找投票最多的帖子 Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24480169/