Laravel 4.2 : 如何在 Laravel 中使用按 SUM 排序
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');
}
如何排序,以便返回结果按 points.I 的最高总和排序还需要知道如何获得每个 post.[=16= 的总分]
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);
我可以知道如何使用查询生成器 and/or 模型关系
来解决这个问题吗
我认为以下查询构建器应该可以帮助您入门..
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();
Eloquent方式:
$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款。
我有 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');
}
如何排序,以便返回结果按 points.I 的最高总和排序还需要知道如何获得每个 post.[=16= 的总分]
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);
我可以知道如何使用查询生成器 and/or 模型关系
来解决这个问题吗我认为以下查询构建器应该可以帮助您入门..
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();
Eloquent方式:
$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款。