来解决它吗
我有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);
QueryBuilder
方法完全相同,只是结果不会是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();