[英]Laravel 4.2 : How to use order by SUM in Laravel
我有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);
Query\\Builder
方式完全一样,只有结果不会是Eloquent模型。
我认为以下查询构建器应该让你开始..
DB::table('posts')
->join('points', 'posts.id', '=', 'points.post_id')
->orderBy('sum(points)')
->groupBy('points.post_id')
->select('points.post_id', 'posts.post', 'sum(points.points) as points')
->paginate(8)
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.