MongoModel.class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. /**
  3. * 洛阳赤炎鹰网络科技有限公司
  4. * https://www.cyyvip.com
  5. * Copyright (c) 2022 赤店商城 All rights reserved.
  6. */
  7. // +----------------------------------------------------------------------
  8. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  9. // +----------------------------------------------------------------------
  10. // | Copyright (c) 2010 http://topthink.com All rights reserved.
  11. // +----------------------------------------------------------------------
  12. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  13. // +----------------------------------------------------------------------
  14. // | Author: liu21st <liu21st@gmail.com>
  15. // +----------------------------------------------------------------------
  16. namespace Think\Model;
  17. use Think\Model;
  18. /**
  19. * MongoModel模型类
  20. * 实现了ODM和ActiveRecords模式
  21. */
  22. class MongoModel extends Model{
  23. // 主键类型
  24. const TYPE_OBJECT = 1;
  25. const TYPE_INT = 2;
  26. const TYPE_STRING = 3;
  27. // 主键名称
  28. protected $pk = '_id';
  29. // _id 类型 1 Object 采用MongoId对象 2 Int 整形 支持自动增长 3 String 字符串Hash
  30. protected $_idType = self::TYPE_OBJECT;
  31. // 主键是否自增
  32. protected $_autoinc = true;
  33. // Mongo默认关闭字段检测 可以动态追加字段
  34. protected $autoCheckFields = false;
  35. // 链操作方法列表
  36. protected $methods = array('table','order','auto','filter','validate');
  37. /**
  38. * 利用__call方法实现一些特殊的Model方法
  39. * @access public
  40. * @param string $method 方法名称
  41. * @param array $args 调用参数
  42. * @return mixed
  43. */
  44. public function __call($method,$args) {
  45. if(in_array(strtolower($method),$this->methods,true)) {
  46. // 连贯操作的实现
  47. $this->options[strtolower($method)] = $args[0];
  48. return $this;
  49. }elseif(strtolower(substr($method,0,5))=='getby') {
  50. // 根据某个字段获取记录
  51. $field = parse_name(substr($method,5));
  52. $where[$field] =$args[0];
  53. return $this->where($where)->find();
  54. }elseif(strtolower(substr($method,0,10))=='getfieldby') {
  55. // 根据某个字段获取记录的某个值
  56. $name = parse_name(substr($method,10));
  57. $where[$name] =$args[0];
  58. return $this->where($where)->getField($args[1]);
  59. }else{
  60. E(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
  61. return;
  62. }
  63. }
  64. /**
  65. * 获取字段信息并缓存 主键和自增信息直接配置
  66. * @access public
  67. * @return void
  68. */
  69. public function flush() {
  70. // 缓存不存在则查询数据表信息
  71. $fields = $this->db->getFields();
  72. if(!$fields) { // 暂时没有数据无法获取字段信息 下次查询
  73. return false;
  74. }
  75. $this->fields = array_keys($fields);
  76. foreach ($fields as $key=>$val){
  77. // 记录字段类型
  78. $type[$key] = $val['type'];
  79. }
  80. // 记录字段类型信息
  81. if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type;
  82. // 2008-3-7 增加缓存开关控制
  83. if(C('DB_FIELDS_CACHE')){
  84. // 永久缓存数据表信息
  85. $db = $this->dbName?$this->dbName:C('DB_NAME');
  86. F('_fields/'.$db.'.'.$this->name,$this->fields);
  87. }
  88. }
  89. // 写入数据前的回调方法 包括新增和更新
  90. protected function _before_write(&$data) {
  91. $pk = $this->getPk();
  92. // 根据主键类型处理主键数据
  93. if(isset($data[$pk]) && $this->_idType == self::TYPE_OBJECT) {
  94. $data[$pk] = new \MongoId($data[$pk]);
  95. }
  96. }
  97. /**
  98. * count统计 配合where连贯操作
  99. * @access public
  100. * @return integer
  101. */
  102. public function count(){
  103. // 分析表达式
  104. $options = $this->_parseOptions();
  105. return $this->db->count($options);
  106. }
  107. /**
  108. * 获取唯一值
  109. * @access public
  110. * @return array | false
  111. */
  112. public function distinct($field, $where=array() ){
  113. // 分析表达式
  114. $this->options = $this->_parseOptions();
  115. $this->options['where'] = array_merge((array)$this->options['where'], $where);
  116. $command = array(
  117. "distinct" => $this->options['table'],
  118. "key" => $field,
  119. "query" => $this->options['where']
  120. );
  121. $result = $this->command($command);
  122. return isset($result['values']) ? $result['values'] : false;
  123. }
  124. /**
  125. * 获取下一ID 用于自动增长型
  126. * @access public
  127. * @param string $pk 字段名 默认为主键
  128. * @return mixed
  129. */
  130. public function getMongoNextId($pk=''){
  131. if(empty($pk)) {
  132. $pk = $this->getPk();
  133. }
  134. return $this->db->getMongoNextId($pk);
  135. }
  136. /**
  137. * 新增数据
  138. * @access public
  139. * @param mixed $data 数据
  140. * @param array $options 表达式
  141. * @param boolean $replace 是否replace
  142. * @return mixed
  143. */
  144. public function add($data='',$options=array(),$replace=false) {
  145. if(empty($data)) {
  146. // 没有传递数据,获取当前数据对象的值
  147. if(!empty($this->data)) {
  148. $data = $this->data;
  149. // 重置数据
  150. $this->data = array();
  151. }else{
  152. $this->error = L('_DATA_TYPE_INVALID_');
  153. return false;
  154. }
  155. }
  156. // 分析表达式
  157. $options = $this->_parseOptions($options);
  158. // 数据处理
  159. $data = $this->_facade($data);
  160. if(false === $this->_before_insert($data,$options)) {
  161. return false;
  162. }
  163. // 写入数据到数据库
  164. $result = $this->db->insert($data,$options,$replace);
  165. if(false !== $result ) {
  166. $this->_after_insert($data,$options);
  167. if(isset($data[$this->getPk()])){
  168. return $data[$this->getPk()];
  169. }
  170. }
  171. return $result;
  172. }
  173. // 插入数据前的回调方法
  174. protected function _before_insert(&$data,$options) {
  175. // 写入数据到数据库
  176. if($this->_autoinc && $this->_idType== self::TYPE_INT) { // 主键自动增长
  177. $pk = $this->getPk();
  178. if(!isset($data[$pk])) {
  179. $data[$pk] = $this->db->getMongoNextId($pk);
  180. }
  181. }
  182. }
  183. public function clear(){
  184. return $this->db->clear();
  185. }
  186. // 查询成功后的回调方法
  187. protected function _after_select(&$resultSet,$options) {
  188. array_walk($resultSet,array($this,'checkMongoId'));
  189. }
  190. /**
  191. * 获取MongoId
  192. * @access protected
  193. * @param array $result 返回数据
  194. * @return array
  195. */
  196. protected function checkMongoId(&$result){
  197. if(is_object($result['_id'])) {
  198. $result['_id'] = $result['_id']->__toString();
  199. }
  200. return $result;
  201. }
  202. // 表达式过滤回调方法
  203. protected function _options_filter(&$options) {
  204. $id = $this->getPk();
  205. if(isset($options['where'][$id]) && is_scalar($options['where'][$id]) && $this->_idType== self::TYPE_OBJECT) {
  206. $options['where'][$id] = new \MongoId($options['where'][$id]);
  207. }
  208. }
  209. /**
  210. * 查询数据
  211. * @access public
  212. * @param mixed $options 表达式参数
  213. * @return mixed
  214. */
  215. public function find($options=array()) {
  216. if( is_numeric($options) || is_string($options)) {
  217. $id = $this->getPk();
  218. $where[$id] = $options;
  219. $options = array();
  220. $options['where'] = $where;
  221. }
  222. // 分析表达式
  223. $options = $this->_parseOptions($options);
  224. $result = $this->db->find($options);
  225. if(false === $result) {
  226. return false;
  227. }
  228. if(empty($result)) {// 查询结果为空
  229. return null;
  230. }else{
  231. $this->checkMongoId($result);
  232. }
  233. $this->data = $result;
  234. $this->_after_find($this->data,$options);
  235. return $this->data;
  236. }
  237. /**
  238. * 字段值增长
  239. * @access public
  240. * @param string $field 字段名
  241. * @param integer $step 增长值
  242. * @return boolean
  243. */
  244. public function setInc($field,$step=1) {
  245. return $this->setField($field,array('inc',$step));
  246. }
  247. /**
  248. * 字段值减少
  249. * @access public
  250. * @param string $field 字段名
  251. * @param integer $step 减少值
  252. * @return boolean
  253. */
  254. public function setDec($field,$step=1) {
  255. return $this->setField($field,array('inc','-'.$step));
  256. }
  257. /**
  258. * 获取一条记录的某个字段值
  259. * @access public
  260. * @param string $field 字段名
  261. * @param string $spea 字段数据间隔符号
  262. * @return mixed
  263. */
  264. public function getField($field,$sepa=null) {
  265. $options['field'] = $field;
  266. $options = $this->_parseOptions($options);
  267. if(strpos($field,',')) { // 多字段
  268. if(is_numeric($sepa)) {// 限定数量
  269. $options['limit'] = $sepa;
  270. $sepa = null;// 重置为null 返回数组
  271. }
  272. $resultSet = $this->db->select($options);
  273. if(!empty($resultSet)) {
  274. $_field = explode(',', $field);
  275. $field = array_keys($resultSet[0]);
  276. $key = array_shift($field);
  277. $key2 = array_shift($field);
  278. $cols = array();
  279. $count = count($_field);
  280. foreach ($resultSet as $result){
  281. $name = $result[$key];
  282. if(2==$count) {
  283. $cols[$name] = $result[$key2];
  284. }else{
  285. $cols[$name] = is_null($sepa)?$result:implode($sepa,$result);
  286. }
  287. }
  288. return $cols;
  289. }
  290. }else{
  291. // 返回数据个数
  292. if(true !== $sepa) {// 当sepa指定为true的时候 返回所有数据
  293. $options['limit'] = is_numeric($sepa)?$sepa:1;
  294. } // 查找符合的记录
  295. $result = $this->db->select($options);
  296. if(!empty($result)) {
  297. if(1==$options['limit']) return reset($result)[$field];
  298. foreach ($result as $val){
  299. $array[] = $val[$field];
  300. }
  301. return $array;
  302. }
  303. }
  304. return null;
  305. }
  306. /**
  307. * 执行Mongo指令
  308. * @access public
  309. * @param array $command 指令
  310. * @return mixed
  311. */
  312. public function command($command, $options=array()) {
  313. $options = $this->_parseOptions($options);
  314. return $this->db->command($command, $options);
  315. }
  316. /**
  317. * 执行MongoCode
  318. * @access public
  319. * @param string $code MongoCode
  320. * @param array $args 参数
  321. * @return mixed
  322. */
  323. public function mongoCode($code,$args=array()) {
  324. return $this->db->execute($code,$args);
  325. }
  326. // 数据库切换后回调方法
  327. protected function _after_db() {
  328. // 切换Collection
  329. $this->db->switchCollection($this->getTableName(),$this->dbName?$this->dbName:C('db_name'));
  330. }
  331. /**
  332. * 得到完整的数据表名 Mongo表名不带dbName
  333. * @access public
  334. * @return string
  335. */
  336. public function getTableName() {
  337. if(empty($this->trueTableName)) {
  338. $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
  339. if(!empty($this->tableName)) {
  340. $tableName .= $this->tableName;
  341. }else{
  342. $tableName .= parse_name($this->name);
  343. }
  344. $this->trueTableName = strtolower($tableName);
  345. }
  346. return $this->trueTableName;
  347. }
  348. /**
  349. * 分组查询
  350. * @access public
  351. * @return string
  352. */
  353. public function group($key, $init, $reduce, $option=array()) {
  354. $option = $this->_parseOptions($option);
  355. //合并查询条件
  356. if(isset($option['where']))
  357. $option['condition'] = array_merge((array)$option['condition'], $option['where']);
  358. return $this->db->group($key, $init, $reduce, $option);
  359. }
  360. /**
  361. * 返回Mongo运行错误信息
  362. * @access public
  363. * @return json
  364. */
  365. public function getLastError(){
  366. return $this->db->command(array('getLastError'=>1));
  367. }
  368. /**
  369. * 返回指定集合的统计信息,包括数据大小、已分配的存储空间和索引的大小
  370. * @access public
  371. * @return json
  372. */
  373. public function status(){
  374. $option = $this->_parseOptions();
  375. return $this->db->command(array('collStats'=>$option['table']));
  376. }
  377. /**
  378. * 取得当前数据库的对象
  379. * @access public
  380. * @return object
  381. */
  382. public function getDB(){
  383. return $this->db->getDB();
  384. }
  385. /**
  386. * 取得集合对象,可以进行创建索引等查询
  387. * @access public
  388. * @return object
  389. */
  390. public function getCollection(){
  391. return $this->db->getCollection();
  392. }
  393. }