Laravel 4.2:如何在Laravel中使用SUM的顺序 [英] Laravel 4.2 : How to use order by SUM in Laravel

查看:88
本文介绍了Laravel 4.2:如何在Laravel中使用SUM的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何排序,以使返回结果按最高点数排序.我还需要知道如何获得每个帖子的点数总和.

How can I order it so that the returning results would be ordered by highest sum of points.I also need to know how I can get the sum of points per post.

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

我想知道如何通过使用查询生成器和/或模型关系来解决

May I know how it would be solved by using query builder and/or model relationships

推荐答案

雄辩的方式:

$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的方法完全相同,只是结果不会是雄辩的模型.

The Query\Builder way is exactly the same, only the result won't be Eloquent models.

这篇关于Laravel 4.2:如何在Laravel中使用SUM的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆