如何在laravel5.2中按顺序使用count

时间:2016-06-15 10:23:29

标签: laravel-5.2

我想按顺序使用count,我使用了以下两种方式

第一

DB::table('user_skill')
        ->join('skill_category', 'user_skill.skill_category_id', '=', 'skill_category.skill_category_id')            
        ->select(DB::raw('user_skill.skill_category_id', 'skill_category.skill_name','count(user_skill.skill_category_id) as totalIds'))
        ->orderBy('totalIds','desc')
        ->groupBy('user_skill.skill_category_id')
        ->get();

第二

DB::table('user_skill')
        ->join('skill_category', 'user_skill.skill_category_id', '=', 'skill_category.skill_category_id')            
        ->select(DB::raw('user_skill.skill_category_id', 'skill_category.skill_name'))
        ->orderBy('count(user_skill.skill_category_id)','desc')
        ->groupBy('user_skill.skill_category_id')
        ->get();

但两者都给出了以下错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'totalIds' in 'order clause'

任何建议,我如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

如果检查原始函数,您将看到它只接受一个参数。

public static function raw($value){        
    return \Illuminate\Database\MySqlConnection::raw($value);
}

此外,你所做的是传递多个参数,这样就不会传递任何东西,而是第一个参数。

您可以像下面一样修复它,

->select(DB::raw('user_skill.skill_category_id, skill_category.skill_name, count(user_skill.skill_category_id) as totalIds'))

或者

->select('user_skill.skill_category_id', 'skill_category.skill_name', DB::raw('count(user_skill.skill_category_id) as totalIds'))