You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgnitor中查询未分配给指定部门的服务问题求助

问题分析与解决方案

错误原因拆解

  1. 字段名不匹配:你定义的services表主键是s_id,但代码中错误使用了sr_id,导致关联查询失效。
  2. 逻辑错误:第一个函数中where_not_in的用法不符合需求,左连接后无法正确筛选出未分配给指定部门的服务。
  3. 原生SQL调用错误:第二个函数中,执行$this->db->query($query)后又调用$this->db->get(),后者会生成无表的SELECT *查询,直接触发1096 No tables used错误。

正确实现方式

方式一:CodeIgniter Active Record 写法

修正字段名,使用子查询筛选未分配的服务:

function get_services_for_assign(){
    $dept_id = $this->uri->segment('2');
    $this->db->select('s_id, s_name');
    $this->db->from('services');
    
    if($dept_id){
        // 子查询获取该部门已分配的服务ID
        $subquery = $this->db->select('ss_s_id')
                             ->from('services_assignments')
                             ->where('ss_d_id', $dept_id)
                             ->get_compiled_select();
        
        $this->db->where_not_in('s_id', $subquery);
    }
    
    // 可选:如果需要筛选显示状态的服务,取消注释下面一行
    //$this->db->where('sr_display', '1');
    
    $data = $this->db->get();
    return $data->result();
}

方式二:原生SQL写法

直接编写正确SQL语句,避免重复调用查询方法:

function get_services_for_assign(){
    $dept_id = $this->uri->segment('2');
    
    if($dept_id){
        $query = "SELECT s.s_id, s.s_name 
                  FROM services s 
                  WHERE s.s_id NOT IN (
                      SELECT ss_s_id 
                      FROM services_assignments 
                      WHERE ss_d_id = ?
                  )";
        // 使用参数绑定防止SQL注入
        $result = $this->db->query($query, array($dept_id))->result();
    } else {
        // 未指定部门时返回所有服务
        $result = $this->db->get('services')->result();
    }
    
    return $result;
}

逻辑说明

两种方式核心逻辑一致:

  • 先获取指定部门已分配的所有服务ID集合
  • 从services表中筛选出不在该集合中的服务,即为未分配给该部门的服务
  • 若未指定部门(uri segment2为空),则返回所有服务

内容的提问来源于stack exchange,提问作者Syam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 11:10:19