CodeIgniter中使用数字作为列别名失效问题求助
解决CodeIgniter中数字列别名不生效的问题
这问题我之前帮同事排查过!核心原因其实是SQL的标识符规则:纯数字或者以数字开头的列别名,直接写会被数据库解析成数值,而不是作为列的别名来识别——这就是为什么字母别名正常,数字别名失效的原因。
解决方案:给数字别名加包裹符
在CodeIgniter的select方法里,把数字别名用反引号(`)(适配MySQL/MariaDB环境)或者双引号(")(适配PostgreSQL等兼容SQL标准的数据库)包裹起来就行。修改后的代码如下:
$this->db->select('Observation.id_observation as `1`'); // 用反引号包裹数字别名 $this->db->from('Observation'); $this->db->join('Enregistrement', 'Enregistrement.id_observation = Observation.id_observation', 'left'); $this->db->where('Observation.id_parcelle', $id_parcelle); $this->db->where('Observation.id_observateur', $user_id); $this->db->where('Observation.date_observation >=', $date_start); $this->db->where('Observation.date_observation <=', $date_end); return $this->db->get()->result();
额外提示:PHP中数字属性的访问
如果后续要访问这个数字别名的字段,用result()返回的对象形式访问会有点麻烦(因为PHP对象属性名不能直接是纯数字),建议改用result_array()返回数组结果,这样就能直接通过$row['1']来访问对应的值:
return $this->db->get()->result_array();
这样不管是前端处理还是后端逻辑,都能更顺畅地拿到数字别名对应的列值。
内容的提问来源于stack exchange,提问作者luden
相关产品推荐
相关产品推荐

