如何从codeigniter中的表中获取用户名

时间:2011-03-06 21:56:22

标签: php mysql codeigniter

我有2个表,一个保存日志,另一个保留用户名。

表一(日志)有

ID|USERID|DATETIME|MESSAGE

表二(用户)有

ID|USERNAME|PASSWORD

在codeigniter模型中我有

    function getRlog(){

    $this->db->limit(100);
    $this->db->order_by("id","desc");
    $this->db->where('type', "reservation");
    $q = $this->db->get('logs');
        if($q->num_rows() > 0) {
        foreach($q->result() as $row){
            $data[] = $row;
        }
    return $data;
   }

}

在控制器中我有......

    function log(){
        if (!$this->ion_auth->is_admin())
    {
        $this->session->set_flashdata('message', 'You must be an admin to view this page');
        redirect('auth/login');
        } else {
        $data ['user'] = $this->ion_auth->get_user();
        $this->load->model('Logs_model');
        $data['logs'] = $this->Logs_model->getRlog();
        $this->load->view('database/log', $data);

        }
}

我希望根据日志表中的 id 用户表中获取用户名。我应该创建一个外键吗?如果我这样做,我如何获得用户名?

1 个答案:

答案 0 :(得分:0)

你可以在你的模型中这样做

function getRlog(){

    $this->db->limit(100);
    $this->db->order_by("id","desc");
    $this->db->where('type', "reservation");
    $q = $this->db->get('logs');
    if($q->num_rows() > 0) {
        $data = array();  //create new data array to be returned
        foreach($q->result() as $row){
            $row->user = $this->ion_auth->get_user($row->userid);  //create new user property that contains user object
            $data[] = $row;  //append to new data array with appended user property
        }
        return $data;
    }
    else {
        return false; //if no results make sure you return something, either false or empty array depending on your needs.
    }
}

这样,您可以从模型返回的日志结果中访问整个用户对象,假设您的控制器保持不变。

查看

foreach($logs as $log) {
    echo $log->user->username;
}

甚至......

foreach($logs as $log) {
    echo $log->user->email; //etc...
}