You need to enable JavaScript to run this app. CodeIgniter关联两表ID后无法获取患者关联名称问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter关联两表ID后无法获取患者关联名称问题咨询

CodeIgniter 关联查询值不显示问题修复

核心问题定位

  • 模型执行逻辑顺序错误:将$this->db->join()方法写在$this->db->query()原生查询执行之后,SQL语句已经生成并跑完,关联逻辑完全没有生效
  • 主表名不匹配:需求中主查询表为attributes,但模型中原生SQL错误使用odontograms作为主表
  • 查询字段冲突:直接使用SELECT *关联两张表时,id、name等同名字段会被互相覆盖,即使关联成功也无法正确获取患者表的字段值
  • 取数路径错误:CodeIgniter返回的result_array()为扁平化关联数组,不会按所属表对字段做嵌套分组,之前尝试的三种取数路径均不匹配实际返回结构

修复方案

1. 修正模型查询逻辑

优先使用查询构造器写法,先定义关联逻辑再执行查询,同时为同名字段设置别名避免冲突,修正后代码如下:

// app/models/Model_attributes.php
public function getAttributeValueData($id = null)
{
    // 明确指定查询字段,用别名区分不同表的同名字段
    $this->db->select(
        'attributes.id,
        attributes.patient_id,
        attributes.name as attr_name,
        attributes.description2,
        attributes.created_at,
        patients.name as patient_name'
    );
    // 先定义左关联,再执行查询
    $this->db->join('patients', 'patients.id = attributes.patient_id', 'left');
    $this->db->where('attributes.patient_id', $id);
    $this->db->order_by('attributes.created_at', 'DESC');
    $query = $this->db->get('attributes');

    return $query->result_array();
}

如果坚持使用原生SQL写法,需要将关联逻辑直接写入SQL语句内部,不能依赖查询构造器的方法追加关联,正确写法示例:

public function getAttributeValueData($id = null)
{
    $sql = "SELECT 
                attributes.id,
                attributes.patient_id,
                attributes.name as attr_name,
                attributes.description2,
                attributes.created_at,
                patients.name as patient_name
            FROM attributes
            LEFT JOIN patients ON patients.id = attributes.patient_id
            WHERE attributes.patient_id = ?
            ORDER BY attributes.created_at DESC";
    $query = $this->db->query($sql, array($id));
    return $query->result_array();
}

2. 修正控制器取数路径

因为查询时已经给患者名称设置了patient_name的别名,直接通过这个键名取值即可,修正后控制器代码如下:

// app/controllers/Attributes.php
$result['data'][$key] = array(
    $value['patient_id'],
    $value['patient_name'], // 替换原尝试的错误取数路径,展示关联的患者名称
    $value['attr_name'],
    $value['description2'],
    $value['created_at'],
    $buttons
);

为什么之前的尝试无法生效

  • $value['patients.name']:返回的数组键名不会包含点号,不存在这个键
  • $value['patients']['name']:CodeIgniter返回的查询结果不会按表名做嵌套数组结构,这个路径完全不存在
  • $patients['name']:循环流程中没有定义这个独立变量,无法获取对应值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.21 11:15:05