高效mongodb的php分页类(不使用skip)
mongodb分页skip+limit分页要先查出所有结果再去跳过,这样如果查询页面越往后效率越低。
如果能够通过查询条件查出每页结果的最后一条记录,在用最后一条记录作为查询条件去查下一页,这样每次都查询页面size条记录,效率不会差。
具体代码如下:包含mongodb.class.php,page.class.php,test.php
mongodb.class.phpmongodb操作类
<?php functionshow_error($message,$status_code=500,$heading='AnErrorWasEncountered') { echo$message,$status_code,PHP_EOL; exit; }
//MongoDB操作类 classDB {
private$CI; private$config_file='MongoDB';
private$connection; private$db; private$connection_string; private$collection=''; private$host; private$port; private$user; private$pass; private$dbname; private$key; private$persist; private$persist_key;
private$selects=array(); private$wheres=array(); private$sorts=array(); private$page_sorts=array();
private$limit=999999; private$offset=0;
/** *-------------------------------------------------------------------------------- *CONSTRUCTOR *-------------------------------------------------------------------------------- * *AutomaticallycheckiftheMongoPECLextensionhasbeeninstalled/enabled. *GeneratetheconnectionstringandestablishaconnectiontotheMongoDB. */
publicfunction__construct($MONGODB_CONFIG) { if(!class_exists('Mongo')) { show_error("TheMongoDBPECLextensionhasnotbeeninstalledorenabled",500); } /** $config['mongo_host']='221.234.43.144'; $config['mongo_port']=27017; $config['mongo_db']='test'; $config['mongo_user']=''; $config['mongo_pass']=''; $config['mongo_persist']=TRUE; * */ $this->connection_string($MONGODB_CONFIG); $this->connect(); }
/** *-------------------------------------------------------------------------------- *Switch_db *-------------------------------------------------------------------------------- * *Switchfromdefaultdatabasetoadifferentdb */
publicfunctionswitch_db($database='') { if(empty($database)) { show_error("ToswitchMongoDBdatabases,anewdatabasenamemustbespecified",500); } $this->dbname=$database; try { $this->db=$this->connection->{$this->dbname}; return(TRUE); } catch(Exception$e) { show_error("UnabletoswitchMongoDatabases:{$e->getMessage()}",500); } }
/** *-------------------------------------------------------------------------------- *SELECTFIELDS *-------------------------------------------------------------------------------- * *DeterminewhichfieldstoincludeORwhichtoexcludeduringthequeryprocess. *Currently,includingandexcludingatthesametimeisnotavailable,sothe *$includesarraywilltakeprecedenceoverthe$excludesarray. Ifyouwantto *onlychoosefieldstoexclude,leave$includesanemptyarray(). * *@usage:$this->mongo_db->select(array('foo','bar'))->get('foobar'); */
publicfunctionselect($includes=array(),$excludes=array()) { if(!is_array($includes)) { $includes=array(); }
if(!is_array($excludes)) { $excludes=array(); }
if(!empty($includes)) { foreach($includesas$col) { $this->selects[$col]=1; } } else { foreach($excludesas$col) { $this->selects[$col]=0; } } return($this); }
/** *-------------------------------------------------------------------------------- *WHEREPARAMETERS *-------------------------------------------------------------------------------- * *Getthedocumentsbasedonthesesearchparameters. The$wheresarrayshould *beanassociativearraywiththefieldasthekeyandthevalueasthesearch *criteria. * *@usage=$this->mongo_db->where(array('foo'=>'bar'))->get('foobar'); */
publicfunctionwhere($wheres=array()) { foreach($wheresas$wh=>$val) { $this->wheres[$wh]=$val; } return($this); }
/** *-------------------------------------------------------------------------------- *WHERE_INPARAMETERS *-------------------------------------------------------------------------------- * *Getthedocumentswherethevalueofa$fieldisinagiven$inarray(). * *@usage=$this->mongo_db->where_in('foo',array('bar','zoo','blah'))->get('foobar'); */
publicfunctionwhere_in($field="",$in=array()) { $this->where_init($field); $this->wheres[$field]['$in']=$in; return($this); }
/** *-------------------------------------------------------------------------------- *WHERE_NOT_INPARAMETERS *-------------------------------------------------------------------------------- * *Getthedocumentswherethevalueofa$fieldisnotinagiven$inarray(). * *@usage=$this->mongo_db->where_not_in('foo',array('bar','zoo','blah'))->get('foobar'); */
publicfunctionwhere_not_in($field="",$in=array()) { $this->where_init($field); $this->wheres[$field]['$nin']=$in; return($this); }
/** *-------------------------------------------------------------------------------- *WHEREGREATERTHANPARAMETERS *-------------------------------------------------------------------------------- * *Getthedocumentswherethevalueofa$fieldisgreaterthan$x * *@usage=$this->mongo_db->where_gt('foo',20); */
publicfunctionwhere_gt($field="",$x) { $this->where_init($field); $this->wheres[$field]['$gt']=$x; return($this); }
/** *-------------------------------------------------------------------------------- *WHEREGREATERTHANOREQUALTOPARAMETERS *-------------------------------------------------------------------------------- * *Getthedocumentswherethevalueofa$fieldisgreaterthanorequalto$x * *@usage=$this->mongo_db->where_gte('foo',20); */
publicfunctionwhere_gte($field="",$x) { $this->where_init($field); $this->wheres[$field]['$gte']=$x; return($this); }
/** *-------------------------------------------------------------------------------- *WHERELESSTHANPARAMETERS *-------------------------------------------------------------------------------- * *Getthedocumentswherethevalueofa$fieldislessthan$x * *@usage=$this->mongo_db->where_lt('foo',20); */
publicfunctionwhere_lt($field="",$x) { $this->where_init($field); $this->wheres[$field]['$lt']=$x; return($this); }
/** *-------------------------------------------------------------------------------- *WHERELESSTHANOREQUALTOPARAMETERS *-------------------------------------------------------------------------------- * *Getthedocumentswherethevalueofa$fieldislessthanorequalto$x * *@usage=$this->mongo_db->where_lte('foo',20); */
publicfunctionwhere_lte($field="",$x) { $this->where_init($field); $this->wheres[$field]['$lte']=$x; return($this); }
/** *-------------------------------------------------------------------------------- *WHEREBETWEENPARAMETERS *-------------------------------------------------------------------------------- * *Getthedocumentswherethevalueofa$fieldisbetween$xand$y * *@usage=$this->mongo_db->where_between('foo',20,30); */
publicfunctionwhere_between($field="",$x,$y) { $this->where_init($field); $this->wheres[$field]['$gte']=$x; $this->wheres[$field]['$lte']=$y; return($this); }
/** *-------------------------------------------------------------------------------- *WHEREBETWEENANDNOTEQUALTOPARAMETERS *-------------------------------------------------------------------------------- * *Getthedocumentswherethevalueofa$fieldisbetweenbutnotequalto$xand$y * *@usage=$this->mongo_db->where_between_ne('foo',20,30); */
publicfunctionwhere_between_ne($field="",$x,$y) { $this->where_init($field); $this->wheres[$field]['$gt']=$x; $this->wheres[$field]['$lt']=$y; return($this); }
/** *-------------------------------------------------------------------------------- *WHERENOTEQUALTOPARAMETERS *-------------------------------------------------------------------------------- * *Getthedocumentswherethevalueofa$fieldisnotequalto$x * *@usage=$this->mongo_db->where_between('foo',20,30); */
publicfunctionwhere_ne($field="",$x) { $this->where_init($field); $this->wheres[$field]['$ne']=$x; return($this); }
/** *-------------------------------------------------------------------------------- *WHEREOR *-------------------------------------------------------------------------------- * *Getthedocumentswherethevalueofa$fieldisinoneormorevalues * *@usage=$this->mongo_db->where_or('foo',array('foo','bar','blegh'); */
publicfunctionwhere_or($field="",$values) { $this->where_init($field); $this->wheres[$field]['$or']=$values; return($this); }
/** *-------------------------------------------------------------------------------- *WHEREAND *-------------------------------------------------------------------------------- * *Getthedocumentswheretheelementsmatchthespecifiedvalues * *@usage=$this->mongo_db->where_and(array('foo'=>1,'b'=>'someexample'); */
publicfunctionwhere_and($elements_values=array()){ foreach($elements_valuesas$element=>$val){ $this->wheres[$element]=$val; } return($this); }
/** *-------------------------------------------------------------------------------- *WHEREMOD *-------------------------------------------------------------------------------- * *Getthedocumentswhere$field%$mod=$result * *@usage=$this->mongo_db->where_mod('foo',10,1); */
publicfunctionwhere_mod($field,$num,$result){ $this->where_init($field); $this->wheres[$field]['$mod']=array($num,$result); return($this); }
/** *-------------------------------------------------------------------------------- *Wheresize *-------------------------------------------------------------------------------- * *Getthedocumentswherethesizeofafieldisinagiven$sizeint * *@usage:$this->mongo_db->where_size('foo',1)->get('foobar'); */
publicfunctionwhere_size($field="",$size="") { $this->_where_init($field); $this->wheres[$field]['$size']=$size; return($this); }
/** *-------------------------------------------------------------------------------- *LIKEPARAMETERS *-------------------------------------------------------------------------------- * *Getthedocumentswherethe(string)valueofa$fieldislikeavalue.Thedefaults *allowforacase-insensitivesearch. * *@param$flags *Allowsforthetypicalregularexpressionflags: * i=caseinsensitive * m=multiline * x=cancontaincomments * l=locale * s=dotall,"."matcheseverything,includingnewlines * u=matchunicode * *@param$enable_start_wildcard *IfsettoanythingotherthanTRUE,astartinglinecharacter"^"willbeprepended *tothesearchvalue,representingonlysearchingforavalueatthestartof *anewline. * *@param$enable_end_wildcard *IfsettoanythingotherthanTRUE,anendinglinecharacter"$"willbeappended *tothesearchvalue,representingonlysearchingforavalueattheendof *aline. * *@usage=$this->mongo_db->like('foo','bar','im',FALSE,TRUE); */
publicfunctionlike($field="",$value="",$flags="i",$enable_start_wildcard=TRUE,$enable_end_wildcard=TRUE) { $field=(string)trim($field); $this->where_init($field); $value=(string)trim($value); $value=quotemeta($value);
if($enable_start_wildcard!==TRUE) { $value="^".$value; }
if($enable_end_wildcard!==TRUE) { $value.="$"; }
$regex="/$value/$flags"; $this->wheres[$field]=newMongoRegex($regex); return($this); }
/** *-------------------------------------------------------------------------------- *ORDERBYPARAMETERS *-------------------------------------------------------------------------------- * *Sortthedocumentsbasedontheparameterspassed.Tosetvaluestodescendingorder, *youmustpassvaluesofeither-1,FALSE,'desc',or'DESC',elsetheywillbe *setto1(ASC). * *@usage=$this->mongo_db->where_between('foo',20,30); */
publicfunctionorder_by($fields=array()) { foreach($fieldsas$col=>$val) { if($val==-1||$val===FALSE||strtolower($val)=='desc') { $this->sorts[$col]=-1; } else { $this->sorts[$col]=1; } } return($this); }
/** *-------------------------------------------------------------------------------- *LIMITDOCUMENTS *-------------------------------------------------------------------------------- * *Limittheresultsetto$xnumberofdocuments * *@usage=$this->mongo_db->limit($x); */
publicfunctionlimit($x=99999){ if($x!==NULL&&is_numeric($x)&&$x>=1) { $this->limit=(int)$x; } return($this); }
/** *-------------------------------------------------------------------------------- *OFFSETDOCUMENTS *-------------------------------------------------------------------------------- * *Offsettheresultsettoskip$xnumberofdocuments * *@usage=$this->mongo_db->offset($x); */
publicfunctionoffset($x=0) { if($x!==NULL&&is_numeric($x)&&$x>=1) { $this->offset=(int)$x; } return($this); }
/** *-------------------------------------------------------------------------------- *GET_WHERE *-------------------------------------------------------------------------------- * *Getthedocumentsbaseduponthepassedparameters * *@usage=$this->mongo_db->get_where('foo',array('bar'=>'something')); */
publicfunctionget_where($collection="",$where=array(),$limit=99999) { return($this->where($where)->limit($limit)->get($collection)); }
/** *-------------------------------------------------------------------------------- *GET *-------------------------------------------------------------------------------- * *Getthedocumentsbaseduponthepassedparameters * *@usage=$this->mongo_db->get('foo',array('bar'=>'something')); */
publicfunctionget($collection="") { if(empty($collection)) { show_error("InordertoretreivedocumentsfromMongoDB,acollectionnamemustbepassed",500); } $results=array(); $documents=$this->db->{$collection}->find($this->wheres,$this->selects)->limit((int)$this->limit)->skip((int)$this->offset)->sort($this->sorts);
$returns=array();
foreach($documentsas$doc): $returns[]=$doc; endforeach; $this->clear(); return($returns);
}
/** *-------------------------------------------------------------------------------- *COUNT *-------------------------------------------------------------------------------- * *Countthedocumentsbaseduponthepassedparameters * *@usage=$this->mongo_db->get('foo'); */
publicfunctioncount($collection="") { if(empty($collection)) { show_error("InordertoretreiveacountofdocumentsfromMongoDB,acollectionnamemustbepassed",500); } $count=$this->db->{$collection}->find($this->wheres)->limit((int)$this->limit)->skip((int)$this->offset)->count(); $this->clear(); return($count); } /** *自增ID实现 *returninsert_id */ privatefunctioninsert_inc($table) { $update=array('$inc'=>array('id'=>1)); $query=array('table'=>$table); $command=array( 'findandmodify'=>'_increase', 'update'=>$update, 'query'=>$query, 'new'=>true, 'upsert'=>true ); $id=$this->db->command($command); return$id['value']['id']; } /** *-------------------------------------------------------------------------------- *INSERT *-------------------------------------------------------------------------------- * *Insertanewdocumentintothepassedcollection * *@usage=$this->mongo_db->insert('foo',$data=array()); */
publicfunctioninsert($collection="",$data=array()){ if(empty($collection)) { show_error("NoMongocollectionselectedtoinsertinto",500); }
if(count($data)==0||!is_array($data)) { show_error("NothingtoinsertintoMongocollectionorinsertisnotanarray",500); }
try { $inc=$this->insert_inc($collection); $data['_id']=$inc; $result=$this->db->{$collection}->insert($data,array('fsync'=>TRUE)); if($result['ok']||$result){ returntrue; } else{ returnfalse; } } catch(MongoCursorException$e) { show_error("InsertofdataintoMongoDBfailed:{$e->getMessage()}",500); }
}
/** *-------------------------------------------------------------------------------- *UPDATE *-------------------------------------------------------------------------------- * *Updateadocumentintothepassedcollection * *@usage=$this->mongo_db->update('foo',$data=array()); */
publicfunctionupdate($collection="",$data=array(),$flage=false) { if(empty($collection)) { show_error("NoMongocollectionselectedtoupdate",500); } if(count($data)==0||!is_array($data)) { show_error("NothingtoupdateinMongocollectionorupdateisnotanarray",500); } unset($data['_id']); if($flage){ $arr=$this->wheres; unset($arr['_id']); if(is_array($arr)){ foreach($arras$key=>$w){ unset($data[$key]); } } } try { $res=$this->db->{$collection}->update($this->wheres,array('$set'=>$data),array('fsync'=>TRUE,'multiple'=>FALSE)); $this->clear(); return$res; } catch(MongoCursorException$e) { show_error("UpdateofdataintoMongoDBfailed:{$e->getMessage()}",500); }
}
/** *-------------------------------------------------------------------------------- *UPDATE_ALL *-------------------------------------------------------------------------------- * *Insertanewdocumentintothepassedcollection * *@usage=$this->mongo_db->update_all('foo',$data=array()); */
publicfunctionupdate_all($collection="",$data=array()){ if(empty($collection)) { show_error("NoMongocollectionselectedtoupdate",500); }
if(count($data)==0||!is_array($data)) { show_error("NothingtoupdateinMongocollectionorupdateisnotanarray",500); }
try { $this->db->{$collection}->update($this->wheres,array('$set'=>$data),array('fsync'=>TRUE,'multiple'=>TRUE)); $this->clear(); return(TRUE); } catch(MongoCursorException$e) { show_error("UpdateofdataintoMongoDBfailed:{$e->getMessage()}",500); }
}
/** *-------------------------------------------------------------------------------- *DELETE *-------------------------------------------------------------------------------- * *deletedocumentfromthepassedcollectionbaseduponcertaincriteria * *@usage=$this->mongo_db->delete('foo',$data=array()); */
publicfunctiondelete($collection,$where) { if(empty($collection)) { show_error("NoMongocollectionselectedtodeletefrom",500); } if(!$where){ show_error("Nodatainputtodelete",500); } try { $this->wheres=$where; $this->db->{$collection}->remove($this->wheres); $this->clear(); return(TRUE); } catch(MongoCursorException$e) { show_error("DeleteofdataintoMongoDBfailed:{$e->getMessage()}",500); }
}
/** *-------------------------------------------------------------------------------- *DELETE_ALL *-------------------------------------------------------------------------------- * *Deletealldocumentsfromthepassedcollectionbaseduponcertaincriteria * *@usage=$this->mongo_db->delete_all('foo',$data=array()); */
publicfunctiondelete_all($collection="") { if(empty($collection)) { show_error("NoMongocollectionselectedtodeletefrom",500); }
try { $this->db->{$collection}->remove($this->wheres,array('fsync'=>TRUE,'justOne'=>FALSE)); $this->clear(); return(TRUE); } catch(MongoCursorException$e) { show_error("DeleteofdataintoMongoDBfailed:{$e->getMessage()}",500); }
}
/** *-------------------------------------------------------------------------------- *ADD_INDEX *-------------------------------------------------------------------------------- * *Ensureanindexofthekeysinacollectionwithoptionalparameters.Tosetvaluestodescendingorder, *youmustpassvaluesofeither-1,FALSE,'desc',or'DESC',elsetheywillbe *setto1(ASC). * *@usage=$this->mongo_db->add_index($collection,array('first_name'=>'ASC','last_name'=>-1),array('unique'=>TRUE)); */
publicfunctionadd_index($collection="",$keys=array(),$options=array()) { if(empty($collection)) { show_error("NoMongocollectionspecifiedtoaddindexto",500); }
if(empty($keys)||!is_array($keys)) { show_error("IndexcouldnotbecreatedtoMongoDBCollectionbecausenokeyswerespecified",500); } foreach($keysas$col=>$val) { if($val==-1||$val===FALSE||strtolower($val)=='desc') { $keys[$col]=-1; } else { $keys[$col]=1; } }
if($this->db->{$collection}->ensureIndex($keys,$options)==TRUE) { $this->clear(); return($this); } else { show_error("AnerroroccuredwhentryingtoaddanindextoMongoDBCollection",500); } }
/** *-------------------------------------------------------------------------------- *REMOVE_INDEX *-------------------------------------------------------------------------------- * *Removeanindexofthekeysinacollection.Tosetvaluestodescendingorder, *youmustpassvaluesofeither-1,FALSE,'desc',or'DESC',elsetheywillbe *setto1(ASC). * *@usage=$this->mongo_db->remove_index($collection,array('first_name'=>'ASC','last_name'=>-1)); */
publicfunctionremove_index($collection="",$keys=array()) { if(empty($collection)) { show_error("NoMongocollectionspecifiedtoremoveindexfrom",500); }
if(empty($keys)||!is_array($keys)) { show_error("IndexcouldnotberemovedfromMongoDBCollectionbecausenokeyswerespecified",500); }
if($this->db->{$collection}->deleteIndex($keys,$options)==TRUE) { $this->clear(); return($this); } else { show_error("AnerroroccuredwhentryingtoremoveanindexfromMongoDBCollection",500); } }
/** *-------------------------------------------------------------------------------- *REMOVE_ALL_INDEXES *-------------------------------------------------------------------------------- * *Removeallindexesfromacollection. * *@usage=$this->mongo_db->remove_all_index($collection); */
publicfunctionremove_all_indexes($collection=""){ if(empty($collection)) { show_error("NoMongocollectionspecifiedtoremoveallindexesfrom",500); }
$this->db->{$collection}->deleteIndexes(); $this->clear(); return($this); }
/** *-------------------------------------------------------------------------------- *LIST_INDEXES *-------------------------------------------------------------------------------- * *Listsallindexesinacollection. * *@usage=$this->mongo_db->list_indexes($collection); */ publicfunctionlist_indexes($collection=""){ if(empty($collection)) { show_error("NoMongocollectionspecifiedtoremoveallindexesfrom",500); } return($this->db->{$collection}->getIndexInfo()); }
/** *-------------------------------------------------------------------------------- *DROPCOLLECTION *-------------------------------------------------------------------------------- * *Removesthespecifiedcollectionfromthedatabase. Becarefulbecausethis * canhavesomeverylargeissuesinproduction! */
publicfunctiondrop_collection($collection="") { if(empty($collection)) { show_error("NoMongocollectionspecifiedtodropfromdatabase",500); } $this->db->{$collection}->drop(); returnTRUE; }
/** *-------------------------------------------------------------------------------- *CONNECTTOMONGODB *-------------------------------------------------------------------------------- * *EstablishaconnectiontoMongoDBusingtheconnectionstringgeneratedin *theconnection_string()method. If'mongo_persist_key'wassettotrueinthe *configfile,establishapersistentconnection. Weallowforonlythe'persist' *optiontobesetbecausewewanttoestablishaconnectionimmediately. */
privatefunctionconnect(){ $options=array(); if($this->persist===TRUE) { $options['persist']=isset($this->persist_key)&&!empty($this->persist_key)?$this->persist_key:'ci_mongo_persist'; }
try { $this->connection=newMongo($this->connection_string,$options); $this->db=$this->connection->{$this->dbname}; return($this); } catch(MongoConnectionException$e) { show_error("UnabletoconnecttoMongoDB:{$e->getMessage()}",500); } }
/** *-------------------------------------------------------------------------------- *BUILDCONNECTIONSTRING *-------------------------------------------------------------------------------- * *Buildtheconnectionstringfromtheconfigfile. */
privatefunctionconnection_string($MONGODB_CONFIG) {
$this->host=trim($MONGODB_CONFIG['HOST']); $this->port=trim($MONGODB_CONFIG['PORT']); $this->user=trim($MONGODB_CONFIG['USER']); $this->pass=trim($MONGODB_CONFIG['PWD']); $this->dbname=trim($MONGODB_CONFIG['DATABASE']); $this->persist=trim($MONGODB_CONFIG['PERSIST']); $this->persist_key=trim($MONGODB_CONFIG['PERSIST_KEY']);
$connection_string="mongodb://";
if(empty($this->host)) { show_error("TheHostmustbesettoconnecttoMongoDB",500); }
if(empty($this->dbname)) { show_error("TheDatabasemustbesettoconnecttoMongoDB",500); }
if(!empty($this->user)&&!empty($this->pass)) { $connection_string.="{$this->user}:{$this->pass}@"; }
if(isset($this->port)&&!empty($this->port)) { $connection_string.="{$this->host}:{$this->port}/{$this->dbname}"; } else { $connection_string.="{$this->host}"; }
$this->connection_string=trim($connection_string); }
/** *-------------------------------------------------------------------------------- *CLEAR *-------------------------------------------------------------------------------- * *Resetstheclassvariablestodefaultsettings */
privatefunctionclear() { $this->selects=array(); $this->wheres=array(); $this->limit=NULL; $this->offset=NULL; $this->sorts=array(); }
/** *-------------------------------------------------------------------------------- *WHEREINITIALIZER *-------------------------------------------------------------------------------- * *Preparesparametersforinsertionin$wheresarray(). */
privatefunctionwhere_init($param) { if(!isset($this->wheres[$param])) { $this->wheres[$param]=array(); } } /** *-------------------------------------------------------------------------------- *设置表 *-------------------------------------------------------------------------------- * 参数: * $table表名 */ publicfunctionset_table($table){ $this->collection=$table; } /** *-------------------------------------------------------------------------------- *获取表名 *-------------------------------------------------------------------------------- */ publicfunctionget_table(){ return$this->collection; } /** *-------------------------------------------------------------------------------- *设置表排序 *-------------------------------------------------------------------------------- * 参数: * $orderby排序 */ publicfunctionset_orderby($orderby){ $this->page_sorts=$orderby; } /** *-------------------------------------------------------------------------------- *获取左边结果集 *-------------------------------------------------------------------------------- * 参数: * $left左边显示的个数 * $last定位当前页的值 * $size页面大小 */ publicfunctionget_left($left,$last,$size=PAGE_SIZE){ if($last){ $order=$this->nor_orderby(); if($this->page_sorts[$this->key]==-1){ $this->where_gt($this->key,$last); }else{ $this->where_lt($this->key,$last); } return$this->limit($left*$size)->order_by($order)->get($this->collection); } } /** *-------------------------------------------------------------------------------- *获取右边结果集 *-------------------------------------------------------------------------------- * 参数: * $right右边显示的个数 * $last定位当前页的值 * $size页面大小 */ publicfunctionget_right($right,$last,$size=PAGE_SIZE){ if($last){ if($this->page_sorts[$this->key]==-1){ $this->where_lte($this->key,$last); }else{ $this->where_gte($this->key,$last); } } return$this->limit($right*$size+1)->order_by($this->page_sorts)->get($this->collection); } /** *-------------------------------------------------------------------------------- *设置key *-------------------------------------------------------------------------------- * 参数: * $key设置索引主键 */ publicfunctionset_key($key){ $this->key=$key; } /** *-------------------------------------------------------------------------------- *求反 *-------------------------------------------------------------------------------- */ privatefunctionnor_orderby(){ foreach($this->page_sortsas$key=>$order){ if($order==-1){ $orderby[$key]=1; }else{ $orderby[$key]=-1; } } return$orderby; } /** *-------------------------------------------------------------------------------- *获取上一页的值 *-------------------------------------------------------------------------------- * 参数: * $last定位当前页的值 * $size页面大小 */ publicfunctionget_prev($last,$size=PAGE_SIZE){ if($last){ if($this->page_sorts[$this->key]==1){ $this->where_lt($this->key,$last)->order_by(array($this->key=>-1)); }else{ $this->where_gt($this->key,$last)->order_by(array($this->key=>1)); } $result=$this->limit($size)->get($this->collection); } return$result[$size-1][$this->key]; } /** *-------------------------------------------------------------------------------- *获取下一页的值 *-------------------------------------------------------------------------------- * 参数: * $last定位当前页的值 * $size页面大小 */ publicfunctionget_next($last,$size=PAGE_SIZE){ if($last){ if($this->page_sorts[$this->key]==1){ $this->where_gte($this->key,$last); }else{ $this->where_lte($this->key,$last); } } $result=$this->limit($size+1)->order_by($this->page_sorts)->get($this->collection); return$result[$size][$this->key]; } /** *-------------------------------------------------------------------------------- *获取最后一页的值 *-------------------------------------------------------------------------------- * 参数: * $size页面大小 */ publicfunctionget_last($size=PAGE_SIZE){ $res=$this->count($this->collection)%$size; $order=$this->nor_orderby(); if($res>0){ $result=$this->limit($res)->order_by($order)->get($this->collection); return$result[$res-1][$this->key]; }else{ $result=$this->limit($size)->order_by($order)->get($this->collection); return$result[$size-1][$this->key]; } } /** *-------------------------------------------------------------------------------- *分页查询 *-------------------------------------------------------------------------------- * 参数: * $last定位当前页的值 * $size页面大小 */ publicfunctionpage_query($last,$size=PAGE_SIZE){ if($last){ if($this->page_sorts[$this->key]==1){ $this->where_gte($this->key,$last); }else{ $this->where_lte($this->key,$last); } } return$this->limit($size)->order_by($this->page_sorts)->get($this->collection); } /** *批量执行代码_插入 *@paramString$collection *@param二维数组$code */ publicfunctionexecute_insert($collection,$code){ //将二维数组分成js格式 $strcode=''; foreach($codeas$k=>$v){ foreach($vas$kk=>$vv){ $strcode.='db.getCollection("'.$collection.'").insert({"'.$kk.'":"'.$vv.'"});'; } } //retrunarray([ok]=>1); return$this->db->execute($code); }
} ?>