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

如何在CodeIgniter中按逗号分隔服务ID筛选医院数据

按服务筛选医院详情的CodeIgniter查询问题

需求:从tbl_hospital表中筛选出同时包含服务ID 10和12的医院,表中services字段存储格式为带方括号的逗号分隔字符串(示例:["10", "12", "20"]),传入筛选参数为["10", "12"]。

你尝试的代码无法正常运行:

$this->db->select('tbl_hospital.*');
$this->db->from('tbl_hospital');
$this->db->where_in('tbl_hospital.services', ["10", "12"], false);
$this->db->get()->result();

问题原因

where_in的逻辑是匹配字段值完全等于数组中的某一个元素,但你的services字段是包含多个ID的字符串,这种方式根本无法匹配到目标记录。

解决方案

根据services字段的存储格式,有两种可行的查询方式:

方式1:使用FIND_IN_SET(适配带方括号的字符串格式)

先去掉字段值的方括号,再逐个检查服务ID是否存在:

$this->db->select('tbl_hospital.*');
$this->db->from('tbl_hospital');

$targetServices = ["10", "12"];
foreach ($targetServices as $serviceId) {
    // 去掉字段值的前后方括号,再用FIND_IN_SET检查存在性
    $this->db->where("FIND_IN_SET('{$serviceId}', REPLACE(REPLACE(services, '[', ''), ']', '')) > 0");
}

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

方式2:使用JSON_CONTAINS(适配JSON格式存储)

如果你的services字段实际是按JSON格式存储的,直接用MySQL的JSON函数更准确:

$this->db->select('tbl_hospital.*');
$this->db->from('tbl_hospital');

$targetServices = ["10", "12"];
foreach ($targetServices as $serviceId) {
    // 用JSON_CONTAINS匹配数组中的元素
    $this->db->where("JSON_CONTAINS(services, '\"{$serviceId}\"')");
}

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

两种方式都是通过循环添加条件,确保所有传入的服务ID都存在于医院的services字段中,从而筛选出同时提供这些服务的医院。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:52:18