我有3张桌子:
Posts
--id
--post
Points
--id
--user_id
--post_id
--points
User(disregard)
--id
--username
我的模型是这样的。
Class Posts extends Eloquent {
function points(){
return $this->hasMany('points', 'post_id');
}
}
Class Points extends Eloquent {
function posts() {
return $this->belongsTo('posts', 'post_id');
}
我怎样才能排序,以便返回的结果按最高点数总和排序。我还需要知道如何获得每个帖子的点数总和。
Post_id | Post | Points<-- SumPoints
5 |Post1 | 100
3 |Post2 | 51
1 |Post3 | 44
4 |Post4 | 32
这是我的代码:
$homePosts = $posts->with("filters")
->with(array("points" => function($query) {
$query->select()->sum("points");
}))->groupBy('id')
->orderByRaw('SUM(points) DESC')
->paginate(8);
我可以知道如何使用查询生成器和/或模型关系来解决它
雄辩的方式:
$posts = Post::leftJoin('points', 'points.post_id', '=', 'posts.id')
->selectRaw('posts.*, sum(points.points) as points_sum')
->orderBy('points_sum', 'desc')
->paginate(8);
The Query\Builder
方式完全一样,只是结果不会是 Eloquent 模型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)