2015-03-25 76 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();