我正在使用 Codeigniter 构建一个应用程序,并且需要一些数据库查询方面的帮助。
我有一个名为 users 的表,其中包含以下字段:
user_id, user_name, user_password, user_email, user_role, user_manager_id
在我的应用程序中,我使用以下命令从用户表中提取所有记录:
function get_clients()
{
$this->db->select('*');
$this->db->where('user_role', 'client');
$this->db->order_by("user_name", "Asc");
$query = $this->db->get("users");
return $query->result_array();
}
这按预期工作,但是当我在 View 中显示结果时,我还想显示一个名为 Manager
的新列,它将显示经理 user_name
字段。
user_manager_id
是同一个表中用户的 ID。
我猜您可以在同一个表上创建外部联接,但不确定。
在 View 中,我显示返回的信息如下:
<table class="table table-striped" id="zero-configuration">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Manager</th>
</tr>
</thead>
<tbody>
<?php
foreach($clients as $row)
{
?>
<tr>
<td><?php echo $row['user_name']; ?> (<?php echo $row['user_username']; ?>)</td>
<td><?php echo $row['user_email']; ?></td>
<td><?php echo $row['???']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
知道如何形成查询并在 View 中显示经理名称吗?
示例:
user_id user_name user_password user_email user_role user_manager_id
1 Ollie adjjk34jcd xxx@hotmail.com client null
2 James djklsdfsdjk xxs@hotmail.com client 1
当我查询数据库时,我想显示这样的结果:
Ollie xxxx@hotmail.com
詹姆斯 xxs@hotmail.com 奥利
最佳答案
您可以使用$this->db->join()
Controller
function get_clients()
{
$this->db->select('u1.* , u2.user_name as manager_user_name');
$this->db->where('u1.user_role', 'client');
$this->db->join('users u2 ', 'u2.user_id = u1.user_manager_id', 'left outer');
$this->db->order_by("u1.user_name", "Asc");
$query = $this->db->get("users u1");
return $query->result_array();
}
查看
<td><?php echo $row['manager_user_name']; ?></td>
**
关于php - MySQL 数据库查询 - Codeigniter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24005951/