如何使用户在会话中拥有多个角色

how to make a user to have more than one role in session

我的数据库中有不同的用户角色。用户注册时,可能会在数据库中插入多个角色。但是当我在会话中保存它时,它只保存了一个角色。在某些示例中,用户有 2 个角色 - 学生和客户,但仅显示为学生。

我的登录控制器是:

<?php
class Home extends CI_Controller {
//some code
 public function login ()
    {
            
     $this->load->model('user_model');
        $user=$this->user_model->login();
        if(count($user) > 0) 
        {
                $this->load->library('session'); 
            
                 $data = array(
                    'username' => $user['username'],
                    'user_id' => $user['user_id'],
                    'is_logged_in' => TRUE
                
                );

            $this->session->set_userdata($data);
        
            $user_role=$this->user_model->user_role();

            $role=$this->session->set_userdata($user_role);

            $user_role = $this->session->userdata('role_id');


            if($user_role == 1)
            {
                  
                 redirect('student/index');
            } 
//and so on for other roles
    }
}
}

在我的模型中,我使用 "row_array"。如果我使用 result_array(),请注意:"undefined index username, user_id in Controller"。我的模型是:

 public function login()
    {
          
        $this->db->where('username', $this->input->post('username'));
        $this->db->where('password',sha1($this->input->post('password')));
        $result=$this->db->get('users');
   
    return $result->row_array();
   
    }
 public function user_role() 
{
   
    $this->db->select('role_id');
    $this->db->where('user_id', $this->session->userdata['user_id']);
    $result=$this->db->get('user_roles');
        return $result->result_array();
   
}

您可以在会话中保存数组。
你可以这样做

$user_role=$this->user_model->user_role();//lets assume it returns the roles array
$this->session->set_userdata('roles'$user_role);//now you can set it inside roles varibale which contains the role array

//now to get the value from session use this

$roles=$this->session->userdata('roles');
//now roles contains the array of roles
//check your current roles info in the $roles array

希望你明白。