繁体   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