在codeigniter中翻译ORDER BY COUNT(*)DESC

function getCategory($year){
  if(!$year){
      $year=2017;
  }

  $q = $this->msdb->query("SELECT category_code, COUNT(*) AS numb
                          FROM easypm_sales_orders WHERE YEAR(sales_date) = $year
                          GROUP BY category_code ORDER BY COUNT(*) DESC");
  return $q->result();
}

So, I have this model function and I want to translate the SQL query bit into codeigniter. I tried:

function getCategory($year){
        if(!$year){
            $year=2017;
        }

        $this->db->select('category_code');
        $this->db->count("* as 'numb'");
        $this->db->from('easypm_sales_orders');
        $this->db->where('YEAR(sales_date)', $year);
        $this->db->group_by('category_code');
        $q = $this->db->order_by('numb', 'desc');

        return $q->result();
    }

but no luck, is there something I'm doing wrong?

I believe it is necessary to use DB::raw() to represent a WHERE clause involving a function of a database column. Also, while it is possible to get a count from a Laravel query without using DB::raw(), if you want to assign a custom alias to that count it is also needed here. Consider the following code:

$this->db->select(DB::raw('count(*) as numb, category_code'))
$this->db->from('easypm_sales_orders');
$this->db->whereRaw('YEAR(sales_date) = ?', $year);
$this->db->group_by('category_code');
$q = $this->db->order_by('numb', 'desc');

return $q->result();

try this

$query = $this->db
    ->select("category_code, count(*) AS numb",false)
    ->from ("easypm_sales_orders")
    ->where("YEAR(sales_date)",$year)
    ->group_by("category_code")
    ->order_by("numb","DESC")
    ->get();

return $query->result();

Codeigniter active record has no count method.
only count_all_results and count_all and they are used differently
You need replace your select options like this and remove $this->db->count("* as 'numb'");

$this->db->select('category_code');
$this->db->select('COUNT(*) numb');

Rest of your code OK.