Laravel 5 > orderBy 上下票之差 > 分页
Laravel 5 > orderBy difference between up and down votes > pagination
假设我有以下数据库设置
用户table
id
name
个帖子table
id
post
票table
id
user_id
post_id
vote (1 = up, -1 = down)
...并且我们还假设我已正确设置每个一对多关系:)
如何查询按赞成票和反对票之差衡量的前 5 个帖子?
像这样的东西会很棒...
$posts = Post::whereHas('votes', function($query) {
$query->orderByRaw('sum(\'vote\'), desc');
})->get();
...我想稍后分页。
正在工作:)
$posts = Post::has('votes')
->leftJoin('votes', 'votes.post_id', '=', 'posts.id')
->selectRaw('posts.*, sum(votes.vote) as votes_sum')
->groupBy('posts.id')
->orderBy('votes_sum', 'desc')
->paginate(5);
假设我有以下数据库设置
用户table
id
name
个帖子table
id
post
票table
id
user_id
post_id
vote (1 = up, -1 = down)
...并且我们还假设我已正确设置每个一对多关系:)
如何查询按赞成票和反对票之差衡量的前 5 个帖子?
像这样的东西会很棒...
$posts = Post::whereHas('votes', function($query) {
$query->orderByRaw('sum(\'vote\'), desc');
})->get();
...我想稍后分页。
正在工作:)
$posts = Post::has('votes')
->leftJoin('votes', 'votes.post_id', '=', 'posts.id')
->selectRaw('posts.*, sum(votes.vote) as votes_sum')
->groupBy('posts.id')
->orderBy('votes_sum', 'desc')
->paginate(5);