codeigniter 在一个函数中连接两个表

wfypjpf4  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(91)

我想把两个表的数据合并到一个表中,并显示两个表的数据。我已经有了加载一个表的函数。有人能修改这个函数代码来得到两个表吗?我只是一个初学者。

模型_用户.php

public function getUserGroup($userId = null) 
    {
        if($userId) {
            $sql = "SELECT * FROM user_group WHERE user_id = ?";
            $query = $this->db->query($sql, array($userId));
            $result = $query->row_array();

            $group_id = $result['group_id'];
            $g_sql = "SELECT * FROM groups WHERE id = ?";
            $g_query = $this->db->query($g_sql, array($group_id));
            $q_result = $g_query->row_array();
            return $q_result;
        }
    }

控制器用户.php

public function index()
    {
        if(!in_array('viewUser', $this->permission)) {
            redirect('dashboard', 'refresh');
        }

        $user_data = $this->model_users->getUserData();

        $result = array();
        foreach ($user_data as $k => $v) {

            $result[$k]['user_info'] = $v;

            $group = $this->model_users->getUserGroup($v['id']);
            $result[$k]['user_group'] = $group;
        }

        $this->data['user_data'] = $result;

        $this->render_template('users/index', $this->data);
    }
nkcskrwz

nkcskrwz1#

给你

$this->db->select("ug.*,g.*");
        $this->db->from("user_group ug");
        $this->db->join('groups g', 'ug.user_id = g.group_id');
        $this->db->where("ug.user_id",1);

        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            $result = $query->result();
        } else {
            $result = null;
        }
        return $result;

相关问题