【问题标题】:Laravel 4.2 : How to use order by SUM in LaravelLaravel 4.2:如何在 Laravel 中使用 SUM 排序
【发布时间】:2015-03-25 05:13:37
【问题描述】:

我有 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);  

我可以知道如何通过使用查询构建器和/或模型关系来解决它

【问题讨论】:

  • 您发布的代码的结果是什么?你想要一个带有模型/关系或原始查询的 ORM 解决方案吗?

标签: php laravel eloquent


【解决方案1】:

雄辩的方式:

$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 模型。

【讨论】:

  • 我必须使用 ->groupBy('posts.id') 才能获得由帖子分隔的结果。我之前是不是有什么问题?
【解决方案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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    相关资源
    最近更新 更多