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_attendancesWHEREtimestamp= [今日时间戳] ANDsection_id= 11 ANDstatusIN (1, 3)
通过where_in方法可以指定字段和待匹配的多个值,完美解决多值匹配的需求。
内容的提问来源于stack exchange,提问作者zak
相关产品推荐
相关产品推荐

