基于列codeigniter对行进行分组

时间:2016-10-27 05:52:48

标签: php mysql codeigniter codeigniter-2

我想根据列对行进行分组。我附上了我的表 我试过,我的问题是,当使用group_by时,它将只返回每个用户的一行。我想通过user_id从这个表组中获取整个数据 模型

 public function get_pdf_print( $start_date, $end_date) {
          $this->db->select('*');
        $this->db->from('jil_invoices');
   $this->db->group_by('jil_invoices.inv_userid');
  $this->db->where('jil_invoices.inv_dated >=', $start_date);
        $this->db->where('jil_invoices.inv_dated <=', $end_date);
  $query = $this->db->get();
return $query->result();
}

this is my table structure

1 个答案:

答案 0 :(得分:1)

如果您想将GROUP BY与userid列一起使用,请注意它不会返回所有行。

我建议您获取所有行,而不是使用PHP进行分组,例如:

在您的模型中:

public function get_pdf_print($start_date, $end_date) {
    $this->db->select('*');
    $this->db->from('jil_invoices');
    $this->db->where('jil_invoices.inv_dated >=', $start_date);
    $this->db->where('jil_invoices.inv_dated <=', $end_date);
    $query = $this->db->get();
    return $query->result_array(); // here i am using result_array function will return result into array.
}

在你的控制器中:

$records = $this->model_yourmodel->get_pdf_print($startDate,$endDate);
$userData = array();
foreach ($records as $key => $value) {
    $userData[$value['inv_userid']][] = $value; // get all record against each user
}