【问题标题】:codeigniter JOIN returing wrong idcodeigniter JOIN 返回错误的 id
【发布时间】:2020-04-03 01:43:13
【问题描述】:

我是 codeigniter 的新手,遇到了一个 JOIN 问题。

我有两张桌子

super_admin_staff 和 super_admin_roles

super_admin_staff 有一个名为“id”的唯一 id 列,它还有一个名为“role”的列

'role' 列对应 super_admin_roles 的 'id' 列。

我的模型:

 function superAdminStaff()
{
    $this->db->select('*');
    $this->db->from('super_admin_staff');
    $this->db->join('super_admin_roles', 'super_admin_staff.role = super_admin_roles.id');


    $query = $this->db->get();

    $result = $query->result();
    return $result;
}

我的班级:

public function index()
{

    if ($this->isSuperAdmin() != true) {
        $this->loadThis();
    } else {

        $this->load->model('super_admin_staff_model'); 

        $data['userRecords'] = $this->super_admin_staff_model->superAdminStaff(); 

        // set up page title and description
        $this->global['pageTitle'] = 'Staff List';
        $this->global['pageDesc'] = 'Add, Edit or Resign Staff';

        $this->loadViews("super_admin/staff", $this->global, $data, null); 
    }
}

我的看法:

<tbody>
      <?php
      if (!empty($userRecords)) {
        foreach ($userRecords as $record) {
          ?>
          <tr>

            <td><img src="<?php echo base_url() . 'uploads/super_admin/' . $record->profile_picture ?>" class="wd-100 rounded-circle bd bd-2"></td>
            <td class="align-middle"><?php echo $record->firstname ?></td>
            <td class="align-middle"><?php echo $record->lastname ?></td>
            <td class="align-middle"><?php echo $record->email ?></td>
            <td class="align-middle"><?php echo $record->phone ?></td>
            <td class="align-middle"><?php echo $record->role ?></td>
            <td class="text-center align-middle">

              <a class="btn btn-sm btn-danger deleteUser" href="<?php echo base_url() . 'super_admin_staff/deletestaff/' . $record->id; ?>" data-userid="<?php echo $record->id; ?>"><i class="fas fa-trash"></i></a>
            </td>
          </tr>
      <?php
        }
      }
      ?>

    </tbody>

一切正常,&lt;?php echo $record-&gt;role ?&gt; 返回角色名称

&lt;?php echo $record-&gt;id ?&gt; 现在被替换为 super_admin_roles 表中的 id,而不是预期的 super_admin_staff。

我要做的就是使用存储在 super_admin_staff.roles 列中的 id 从 super_admin_roles 获取角色名称,并且仍然使用 super_admin_staff 表中的 id,这样我就可以根据 id 删除员工。

【问题讨论】:

标签: php mysql codeigniter join


【解决方案1】:

id 列不明确,因为它存在于查询所涉及的两个表中。

一种解决方案是枚举您希望查询返回的列。表别名也可以方便地缩短查询。

比如:

$this->db->select('s.firstname, s.last_name, s.email, s.email, s.phone, s.role, s.id')
$this->db->from('super_admin_staff as s');
$this->db->join('super_admin_roles as r', 's.role = r.id');

我不确定您是否真的需要来自 super_admin_roles 表的列。如果你这样做,只需将它们添加到select

【讨论】:

  • 感谢@GMB 工作。我确实必须将r.role 添加到select
猜你喜欢
  • 2019-05-31
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 2019-11-11
  • 1970-01-01
相关资源
最近更新 更多