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

PHP CodeIgniter中如何在查询条件中包含多个值(状态字段示例)

解决CodeIgniter查询中多status值匹配的问题

原代码通过关联数组传递查询条件,只能实现单个status值的匹配。要同时匹配status=1和status=3,需要使用CodeIgniter Active Record的where_in方法来实现IN查询,具体修改方式如下:

方式一:保留原条件数组,追加多值匹配

public function get_tertiarylevel_present() {
    $checker = array(
        'timestamp' => strtotime(date('Y-m-d')),
        'section_id' => 11
    );
    // 追加status的多值匹配条件
    $tertiarylevel_present = $this->db->where_in('status', [1, 3])
                                      ->get_where('daily_attendances', $checker);
    return $tertiarylevel_present->num_rows();
}

方式二:全链式调用组合条件

如果觉得拆分条件更清晰,也可以直接用链式调用组合所有查询条件:

public function get_tertiarylevel_present() {
    $tertiarylevel_present = $this->db->where('timestamp', strtotime(date('Y-m-d')))
                                      ->where('section_id', 11)
                                      ->where_in('status', [1, 3])
                                      ->get('daily_attendances');
    return $tertiarylevel_present->num_rows();
}

逻辑说明

两种方式最终生成的SQL逻辑一致,等价于:

SELECT * FROM daily_attendances WHERE timestamp = [今日时间戳] AND section_id = 11 AND status IN (1, 3)

通过where_in方法可以指定字段和待匹配的多个值,完美解决多值匹配的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:31:09