Codeigniter - 对三个表

时间:2015-12-11 13:14:06

标签: php mysql codeigniter codeigniter-3

我有三张桌子如下。主键突出显示,外键以斜体显示

  1. projecttasks [ projecttasksid projectstructureid assignto ,任务名称]

  2. projectstructure [ projectstructureid projectid ,structurename]

  3. 项目 [ projectid ,projectname]

  4. 我可以通过比较'assignto'和userID形成会话数组的项目任务。 这样我就可以将任务分配给登录用户。

    以Codeigniter方式为登录用户/'assignto'字段获取'项目结构'和'项目'的最佳方法是什么。

    我想写, get_structures()和 get_projects()

    代码,

    $user_id    = $this->session->userdata('userID');
    
    $data       = array('main_content'  => 'view_project_tasks_page',
                        'tasks'     => $this->projects->get_project_tasks($user_id),
                        'structures'    => $this->projects->get_structures(),
                        'projects'  => $this->projects->get_projects()  );
    
    $this->load->view('template', $data);
    

    模型 - get_project_tasks($ user_id)

    function get_project_tasks($user_id)
    {
    $rules = array('assignto'   => $user_id );
    
    $this->db->select()->from('projecttasks')->where($rules);
    $sql_stmt = $this->db->get();
    return $sql_stmt->result();
    }
    

1 个答案:

答案 0 :(得分:0)

您搜索的是简单的右连接

In" CodeIgniter方式"它应该看起来像这样(未经测试)

function get_structures($user_id) {
    $rules = array('projecttasks.assignto' => $user_id );

    $this->db->select('projectstructure.*')
        ->from('projectstructure')
        ->join('projecttasks', 'projecttasks.projectstructureid = projectstructure.projectstructureid')
        ->where($rules);

    $sql_stmt = $this->db->get();
    return $sql_stmt->result();
}

function get_projects($user_id) {
    $rules = array('projecttasks.assignto' => $user_id );

    $this->db->select('project.*')
        ->from('projectstructure')
        ->join('projecttasks', 'projecttasks.projectstructureid = projectstructure.projectstructureid')
        ->join('project', 'projecttasks.projectid = project.projectid')
        ->where($rules);

    $sql_stmt = $this->db->get();
    return $sql_stmt->result();
}