在ThinkPHP中,where方法可传入where数组条件,现在需要两个where数组条件之间使用or逻辑执行sql查询,也就是:
$where['xx']=3;
$where['yy']=9;
$condition['ww']=33;
$condition['zz']=99;
现在需要条件是$where or $condition,ThinkPHP中如何表达呢?
这里用到ThinkPHP的组合查询:
$User = M("User"); // 实例化User对象
$map['id'] = array('neq',1);
$map['name'] = 'ok';
$map['_string'] = 'status=1 AND score>10';
$map['_logic'] = 'OR';
$User->where($map)->select();
这里$map[‘_string’]貌似只能传字符串形式,不能传数组,这里希望两个条件都是数组,有两个办法,一个是把数组自己拼接成字符串,另一个办法使用buildSql方法得到其中一个条件下生成的sql,用正则提取其中需要的sql语句。
以下示例是第二个方法:
private function wait_handle_nums($bo_seller_id){
$where_90 = array();
$where_90['bo_deal_status'] = 85;
$where_90['bo_last_modify'] = array(array('gt',date('Y-m-d H:i:s',strtotime('-14 days'))),array('lt',date('Y-m-d H:i:s',strtotime('-13 days'))));
$where_90['bo_seller_id'] = $this->uid;
$where_90 = M('back_order')->where($where_90)->buildSql();
$where_90 = strstr($where_90,'WHERE');
$preg_match = preg_match('/WHERE(.*)/', $where_90, $matches);
if($preg_match){
$where_90 = $matches[1];
$where_90 = '('.$where_90;
}
$where = array();
$where['bo_deal_status'] = 62;
$where['bo_last_modify'] = array(array('gt',date('Y-m-d H:i:s',strtotime('-3 days'))),array('lt',date('Y-m-d H:i:s',strtotime('-2 days'))));
$where['bo_seller_id'] = $this->uid;
$map['_complex'] = $where;
$map['_string'] = $where_90;
$map['_logic'] = 'OR';
$field = 'COUNT(*) as refund_nums,bo_seller_id';
$re = M('back_order')->where($map)->field($field)->find();
return $re['refund_nums'];
}
得到的执行的sql语句是:
SELECT COUNT(*) as refund_nums,`bo_seller_id`
FROM `js_back_order`
WHERE ( ( `bo_deal_status` = 62 ) AND ( (`bo_last_modify` > '2015-07-10 08:48:20') AND (`bo_last_modify` < '2015-07-11 08:48:20') ) )
OR
( ( ( `bo_deal_status` = 85 ) AND ( (`bo_last_modify` > '2015-06-29 08:48:20') AND (`bo_last_modify` < '2015-06-30 08:48:20') ) ) )
两个where条件直接OR.