我正在尝试从2个相关的数据库表中获取数据。部门和职能:每个部门都有多个职能。
我想在同一页面上显示手风琴中的所有数据。
直到现在,代码的工作方式如下: 在控制器中声明变量部门,并且在foreach循环中,我已经在变量中调用了Functions模型。
控制器:
public function index(){
//Data variable declarations
$data['page_title'] = "Departments and Functions";
$data['page_subtitle'] = "choose an occupation for the list of users assigned";
//Data variable declaration - from models
$data['departments'] = $this->Department->get_all('departments');
$this->load->view('layouts/header');
$this->load->view('layouts/title', $data);
$this->load->view('layouts/aside');
$this->load->view('departments/index', $data);
$this->load->view('layouts/footer');
}
在这里,我想添加Function-> get_by_department_id()方法。如何动态获取ID?
职业模式方法:
public function get_by_fk($table = 'occupations', $fk = "department_id" , $fk_value=$department->department_id){
$this->db->select('*');
$this->db->from($table);
$this->db->where($fk, $fk_value);
$query = $this->db->get();
return $result = $query->result();
}
答案 0 :(得分:0)
尝试使用左联接
function get_departments_and_functions() {
$sql = 'SELECT `deptartments`.*, `functions`.*
FROM `departments` LEFT JOIN `functions`
ON `functions`.`deptartments_id` = `departments`.`id`';
return $this->db->query($sql)->result();
}
您还可以查询部门,然后遍历部门并查询以获取功能。然后,您将手动构建结果集。