将我的两个mysql调用减少到一个

时间:2014-02-22 14:10:48

标签: php mysql codeigniter

使用codeigniter(php)我想转到一个名为task的表,获取表中的最新结果,并将该行中的数据添加到我传递给视图的数组中。我有一个丑陋的黑客来完成这项工作(如下所示)。基本上我要去桌子询问最近的日期,然后使用它来再次查询表格以获取我想要的数据。理想情况下,这应该是对数据库的一次调用。

理想情况下,我希望能够从表格行中检索所有内容,而不是像我这里一样只检索一列 - 这在模型中很简单,但令我困惑的是如何将其集成到控制器中以便返回的数组与发送到视图的数组集成

控制器:

public function index()
{   
    //Load models
    $this->load->model('project_model');
    $this->load->model('task_model');

    $flasks = $this->task_model->get_user_tasks_two($this->session->userdata('user'));

    foreach($flasks as $key => $value){
        //get last task
        $task2 = $this->task_model->get_last_task_date($value['project_id']);

        $task3 = $this->task_model->get_last_task_details($task2 , $value['project_id']);
        $flasks[$key]['flask_type'] = $task3;

    }
    $data['tasks'] = $flasks;

    // Load View
    $this->load->view('dashboard', $data);

}

模型:

public function get_user_tasks_two($user)
{
    $this->db->select(' project.id as project_id, project.name as project_name, project.archive as project_archive');
    $this->db->from('project');
    $this->db->join('user_project', 'project.id = user_project.project AND user_project.user = '.$user.'');
    $this->db->order_by('id', 'asc');
    $get = $this->db->get();

    if($get->num_rows > 0) return $get->result_array();
    return array();
}

public function get_last_task_date($id)
{
    $this->db->select_max('date_created');
    $this->db->from('task');
    $this->db->where('project_id', $id);

    $get = $this->db->get();
    $ret = $get->row();
    return $ret->date_created;
}

public function get_last_task_details($date, $id)
{
    $this->db->select('user_name');  
    $this->db->from('task');
    $this->db->where('date_created', $date);
    $this->db->where('project_id', $id);

    $get = $this->db->get();
    $ret = $get->row();
    return $ret->user_name;
}

1 个答案:

答案 0 :(得分:1)

首先在phpmyadmin / mysql工具中尝试此查询

select 
        p.id as project_id, 
        p.name as project_name, 
        p.archive as project_archive,
            t.task_name, 
            t.user_name,
            t.date_created
from 
        project p 
join 
            task t 
on 
           p.id=t.project_id and    
           t.id> (
               select id from tasks  where t.project_id = p.id order by id DESC LIMIT 1
               )