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

CodeIgniter PHP:数据库逗号分隔列数据获取失败排查

问题原因

你用where_in("category", $lid)的逻辑是匹配category字段值完全等于$lid数组里的某一项,但你的category是逗号分隔的字符串(比如"1,3,5"),和数组里的单个值(比如3)不相等,所以查不到正确结果。

解决方案

针对MySQL里的逗号分隔字段,得用FIND_IN_SET函数来判断值是否在字符串里,CodeIgniter里可以这么写:

情况1:$lid是单个分类ID

$this->db->select('*');
$this->db->where("pc", $mid);
$this->db->where("FIND_IN_SET('{$lid}', category) > 0");
$this->db->from('product');
$query = $this->db->get();
return $query->result();

情况2:$lid是多个分类ID的数组

如果要匹配数组里任意一个ID,就循环拼接条件:

$this->db->select('*');
$this->db->where("pc", $mid);

$where_conditions = [];
foreach ($lid as $id) {
    $where_conditions[] = "FIND_IN_SET('{$id}', category) > 0";
}
// 用OR连接多个FIND_IN_SET条件
$this->db->where('(' . implode(' OR ', $where_conditions) . ')');

$this->db->from('product');
$query = $this->db->get();
return $query->result();
额外建议

逗号分隔字段的设计不符合数据库规范,查询时没法用索引,数据量大了会很慢。如果可以的话,建议重构表结构:新建一个product_category关联表,存product_id和category_id的对应关系,这样查询效率更高,也更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:00:05