Laravel获得订单

时间:2014-09-02 05:09:36

标签: php mysql laravel laravel-4 eloquent

我的数据库中有一个表USERS和Table POSTS。

关系(类用户):

public function Posts() {
    return $this->hasMany('Post', 'uid', 'id');
}

我的问题是:如何查询用户并根据帖子数量对其进行排序?如何显示其排名位置?

例如

RANK_POS    UID    USER    NUMBER_OF_POSTS
1           5      USER5   23
2           3      USER3   20
3           6      USER6   2
4           1      USER7   2
5           2      USER2   0

所以,我需要为所有用户计算帖子,并按帖子数量排序,并生成排名位置。

我试过这个

public static function Rank() {
    return DB::table('users')
        ->leftJoin('posts', 'users.id', '=', 'posts.user')            
        ->select(DB::raw('users.id, count(posts.id) as POSTS, users.name, users.surname, users.nickname'))
        ->groupBy('user.id');
}

这给了我或多或少好的结果,但我仍然无法获得排名位置,并且无法通过POSTS订购。

如果我尝试添加订单

public static function Rank() {
    return DB::table('users')
        ->leftJoin('link_analytics', 'users.id', '=', 'link_analytics.user')            
        ->select(DB::raw('users.id, count(link_analytics.id) as CONVERSIONS, users.name, users.surname, users.nickname'))
        ->groupBy('link_analytics.user')
        ->orderBy('POSTS');
}

它给我一个错误UNKNOWN COLUMN' POSTS'

1 个答案:

答案 0 :(得分:0)

public function Posts() {
    return DB::select("SELECT @curRow := @curRow + 1 AS RANK_POS, a.id as uid, a.user, 
                        IFNULL(b.NUMBER_OF_POSTS, 0) AS NUMBER_OF_POSTS
                        FROM users AS a
                        LEFT JOIN (
                           SELECT uid, count(*) as NUMBER_OF_POSTS
                           FROM posts
                           GROUP BY uid
                        ) AS b ON a.id = b.uid  
                        JOIN  (SELECT @curRow := 0) r
                        order by NUMBER_OF_POSTS desc ");
        }