Thinkphp使用mongodb数据库实现多条件查询方法 |
有个项目用了mongodb数据库,查询条件有and也有or,按Thinkphp官方手册,使用复合查询(_complex),getLastSql输出查询语句,发现查询条件是空的.用字符串模式查询(_string),请求字符串查询(_query)无法满足需求.估计用mongodb的用户不多,thinkphp官方对这方面支持也不够.打开thinkphp的mongodb驱动,Thinkphp/Extend/Driver/Db/DbMongo.class.php,找到protected function parseThinkWhere($key,$val)方法,可以发现,switch里没有_complex,也就是说,Thinkphp使用mongodb时,根本不支持复合查询.加上: 复制代码 代码如下: case _complex://复合查询 $arr = array(); foreach ($val as $nkey=>$nval){ if( strpos($nkey,_)!=0) { $parseArr=$this->parseWhereItem($nkey,$nval); //转换成对象 $obj=new stdClass(); foreach ($parseArr as $pkey=>$pval) { $obj->$pkey=$pval; } array_push($arr, $obj); } } if(isset($val[_logic]) && strtolower($val[_logic]) == or ) { unset($val[_logic]); $query[$or] = $arr; } break; 这里之所以要转换成对象,是因为使用thinkphp使用json_encode函数生成查询语句,但是如果数组元素带key,json_encode函数会把数组转换成对象的形式,mongodb不能识别.因为目前只用到or,所以,代码只对or作了处理. 复制代码 代码如下: foreach ($where as $key=>$val){ if(_id != $key && 0===strpos($key,_)) { // 解析特殊条件表达式 //原 $query=$this->parseThinkWhere($key,$val); $query = array_merge($query,$this->parseThinkWhere($key,$val)); }else{ // 查询字段的安全过滤 if(!preg_match(/^[A-Z_\|\&\-.a-z0-9]+$/,trim($key))){ throw_exception(L(_ERROR_QUERY_).:.$key); } $key = trim($key); if(strpos($key,|)) { $array = explode(|,$key); $str = array(); foreach ($array as $k){ $str[] = $this->parseWhereItem($k,$val); } $query[$or] = $str; }elseif(strpos($key,&)){ $array = explode(&,$key); $str = array(); foreach ($array as $k){ $str[] = $this->parseWhereItem($k,$val); } $query = array_merge($query,$str); }else{ $str = $this->parseWhereItem($key,$val); $query = array_merge($query,$str); } } } 解析特殊条件表达式时,源代码里是$query=$this->parseThinkWhere($key,$val);当特殊表达式在where数组里不是第一个元素时,就出错了,else里的代码得到的$query数组,都没了. |