2015-03-25 45 views
3

使用顺序我有3个表:Laravel 4.2:如何通过SUM在Laravel

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_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); 

我可以知道它将如何使用查询构建器和/或模型关系

+0

您发布的代码的结果是什么?你想要一个带有模型/关系或原始查询的ORM解决方案吗? – nozzleman 2015-03-25 06:16:18

回答

3

雄辩的语言:

$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方式完全一样,只有结果不会是雄辩的模式。

+0

我不得不使用 - > groupBy('posts.id')来获得由帖子分隔的结果。我之前有什么不对吗? – johnnydoe82 2016-04-11 11:26:35

2

我觉得下面的查询建设者应该让你来解决开始..

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();