簡體   English   中英

Codeigniter - 多個 Where 子句(代碼重構)

[英]Codeigniter - Multiple Where Clause (Code Refactor)

我正在嘗試從表中獲取數據並且應該計算它的編號。 的學生價值。

輸出如下:

     No. of Students per course
BSCS  3
BSIS  1
CT    2

course_code:BSCS = 3,BSIS = 1,CT = 2

我使用了多個 where 子句,但它不起作用。 有人可以幫助我嗎? 謝謝!

控制器

     public function enrollment_summary()
      {
        $data['title'] = 'Enrollment Summary';
        $this->load->model('report_model');
        $data['bscs'] = $this->report_model->get_studentsPerCourse();
        $data['bsis'] = $this->report_model->get_studentsPerCourse();
        $data['ct'] = $this->report_model->get_studentsPerCourse();
        $this->load->view('report_enrollment_summary', $data);
      }

模型

    public function get_studentsPerCourse()
  {
    $bscs = $this->input->post('students');
    $bsis = $this->input->post('students');
    $ct = $this->input->post('students');
    $this->db->select('*');
    $this->db->from('students');
    $this->db->where('course_code', 'BSCS', $bscs);
    $this->db->where('course_code', 'BSIS', $bsis);
    $this->db->where('course_code', 'ct', $ct);
    return $this->db->count_all_results();
  }

您正在尋找的相應 MySQL 查詢是

SELECT
    course_code,
    COUNT(0) AS student_count
FROM students
WHERE course_code IN ('BSCS', 'BSIS', 'ct')
GROUP BY course_code;

現在您可以將其轉換為等效的 codeigniter 查詢。

// Model code
public function get_studentsPerCourse()
{
    $bscs = $this->input->post('students');
    $bsis = $this->input->post('students');
    $ct = $this->input->post('students');

    $this->db->select('course_code, COUNT(0) AS student_count');
    $this->db->from('students');
    $this->db->where_in('course_code', ['BSCS', 'BSIS', 'ct']);
    $this->db->group_by("course_code");

    return $this->db->get();
}

現在在控制器中,您可以循環並將其分配給變量;

 public function enrollment_summary()
      {
        $data['title'] = 'Enrollment Summary';
        $this->load->model('report_model');

        $result = $this->report_model->get_studentsPerCourse();

        foreach ($result ->getResult() as $row)
        {
            $data[$row->course_code] = $row->student_count;
        }
        // make sure you take care of case sensitivity if required.

        $this->load->view('report_enrollment_summary', $data);
      }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM