Model.class.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace Think;
  12. /**
  13. * ThinkPHP Model模型类
  14. * 实现了ORM和ActiveRecords模式
  15. */
  16. class Model {
  17. // 当前数据库操作对象
  18. protected $db = null;
  19. // 数据库对象池
  20. private $_db = array();
  21. // 主键名称
  22. protected $pk = 'id';
  23. // 主键是否自动增长
  24. protected $autoinc = false;
  25. // 数据表前缀
  26. protected $tablePrefix = null;
  27. // 模型名称
  28. protected $name = '';
  29. // 数据库名称
  30. protected $dbName = '';
  31. //数据库配置
  32. protected $connection = '';
  33. // 数据表名(不包含表前缀)
  34. protected $tableName = '';
  35. // 实际数据表名(包含表前缀)
  36. protected $trueTableName = '';
  37. // 最近错误信息
  38. protected $error = '';
  39. // 字段信息
  40. protected $fields = array();
  41. // 数据信息
  42. protected $data = array();
  43. // 查询表达式参数
  44. protected $options = array();
  45. protected $_validate = array(); // 自动验证定义
  46. protected $_auto = array(); // 自动完成定义
  47. protected $_map = array(); // 字段映射定义
  48. protected $_scope = array(); // 命名范围定义
  49. // 是否自动检测数据表字段信息
  50. protected $autoCheckFields = true;
  51. // 是否批处理验证
  52. protected $patchValidate = false;
  53. // 链操作方法列表
  54. protected $methods = array('strict','order','alias','having','group','lock','distinct','auto','filter','validate','result','token','index','force');
  55. /**
  56. * 架构函数
  57. * 取得DB类的实例对象 字段检查
  58. * @access public
  59. * @param string $name 模型名称
  60. * @param string $tablePrefix 表前缀
  61. * @param mixed $connection 数据库连接信息
  62. */
  63. public function __construct($name='',$tablePrefix='',$connection='') {
  64. // 模型初始化
  65. $this->_initialize();
  66. // 获取模型名称
  67. if(!empty($name)) {
  68. if(strpos($name,'.')) { // 支持 数据库名.模型名的 定义
  69. list($this->dbName,$this->name) = explode('.',$name);
  70. }else{
  71. $this->name = $name;
  72. }
  73. }elseif(empty($this->name)){
  74. $this->name = $this->getModelName();
  75. }
  76. // 设置表前缀
  77. if(is_null($tablePrefix)) {// 前缀为Null表示没有前缀
  78. $this->tablePrefix = '';
  79. }elseif('' != $tablePrefix) {
  80. $this->tablePrefix = $tablePrefix;
  81. }elseif(!isset($this->tablePrefix)){
  82. $this->tablePrefix = C('DB_PREFIX');
  83. }
  84. // 数据库初始化操作
  85. // 获取数据库操作对象
  86. // 当前模型有独立的数据库连接信息
  87. $this->db(0,empty($this->connection)?$connection:$this->connection,true);
  88. }
  89. /**
  90. * 自动检测数据表信息
  91. * @access protected
  92. * @return void
  93. */
  94. protected function _checkTableInfo() {
  95. // 如果不是Model类 自动记录数据表信息
  96. // 只在第一次执行记录
  97. if(empty($this->fields)) {
  98. // 如果数据表字段没有定义则自动获取
  99. if(C('DB_FIELDS_CACHE')) {
  100. $db = $this->dbName?:C('DB_NAME');
  101. $fields = F('_fields/'.strtolower($db.'.'.$this->tablePrefix.$this->name));
  102. if($fields) {
  103. $this->fields = $fields;
  104. if(!empty($fields['_pk'])){
  105. $this->pk = $fields['_pk'];
  106. }
  107. return ;
  108. }
  109. }
  110. // 每次都会读取数据表信息
  111. $this->flush();
  112. }
  113. }
  114. /**
  115. * 获取字段信息并缓存
  116. * @access public
  117. * @return void
  118. */
  119. public function flush() {
  120. // 缓存不存在则查询数据表信息
  121. $this->db->setModel($this->name);
  122. $fields = $this->db->getFields($this->getTableName());
  123. if(!$fields) { // 无法获取字段信息
  124. return false;
  125. }
  126. $this->fields = array_keys($fields);
  127. unset($this->fields['_pk']);
  128. foreach ($fields as $key=>$val){
  129. // 记录字段类型
  130. $type[$key] = $val['type'];
  131. if($val['primary']) {
  132. // 增加复合主键支持
  133. if (isset($this->fields['_pk']) && $this->fields['_pk'] != null) {
  134. if (is_string($this->fields['_pk'])) {
  135. $this->pk = array($this->fields['_pk']);
  136. $this->fields['_pk'] = $this->pk;
  137. }
  138. $this->pk[] = $key;
  139. $this->fields['_pk'][] = $key;
  140. } else {
  141. $this->pk = $key;
  142. $this->fields['_pk'] = $key;
  143. }
  144. if($val['autoinc']) $this->autoinc = true;
  145. }
  146. }
  147. // 记录字段类型信息
  148. $this->fields['_type'] = $type;
  149. // 2008-3-7 增加缓存开关控制
  150. if(C('DB_FIELDS_CACHE')){
  151. // 永久缓存数据表信息
  152. $db = $this->dbName?:C('DB_NAME');
  153. F('_fields/'.strtolower($db.'.'.$this->tablePrefix.$this->name),$this->fields);
  154. }
  155. }
  156. /**
  157. * 设置数据对象的值
  158. * @access public
  159. * @param string $name 名称
  160. * @param mixed $value 值
  161. * @return void
  162. */
  163. public function __set($name,$value) {
  164. // 设置数据对象属性
  165. $this->data[$name] = $value;
  166. }
  167. /**
  168. * 获取数据对象的值
  169. * @access public
  170. * @param string $name 名称
  171. * @return mixed
  172. */
  173. public function __get($name) {
  174. return isset($this->data[$name])?$this->data[$name]:null;
  175. }
  176. /**
  177. * 检测数据对象的值
  178. * @access public
  179. * @param string $name 名称
  180. * @return boolean
  181. */
  182. public function __isset($name) {
  183. return isset($this->data[$name]);
  184. }
  185. /**
  186. * 销毁数据对象的值
  187. * @access public
  188. * @param string $name 名称
  189. * @return void
  190. */
  191. public function __unset($name) {
  192. unset($this->data[$name]);
  193. }
  194. /**
  195. * 利用__call方法实现一些特殊的Model方法
  196. * @access public
  197. * @param string $method 方法名称
  198. * @param array $args 调用参数
  199. * @return mixed
  200. */
  201. public function __call($method,$args) {
  202. if(in_array(strtolower($method),$this->methods,true)) {
  203. // 连贯操作的实现
  204. $this->options[strtolower($method)] = $args[0];
  205. return $this;
  206. }elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
  207. // 统计查询的实现
  208. $field = isset($args[0])?$args[0]:'*';
  209. return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method);
  210. }elseif(strtolower(substr($method,0,5))=='getby') {
  211. // 根据某个字段获取记录
  212. $field = parse_name(substr($method,5));
  213. $where[$field] = $args[0];
  214. return $this->where($where)->find();
  215. }elseif(strtolower(substr($method,0,10))=='getfieldby') {
  216. // 根据某个字段获取记录的某个值
  217. $name = parse_name(substr($method,10));
  218. $where[$name] =$args[0];
  219. return $this->where($where)->getField($args[1]);
  220. }elseif(isset($this->_scope[$method])){// 命名范围的单独调用支持
  221. return $this->scope($method,$args[0]);
  222. }else{
  223. E(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
  224. return;
  225. }
  226. }
  227. // 回调方法 初始化模型
  228. protected function _initialize() {}
  229. /**
  230. * 对保存到数据库的数据进行处理
  231. * @access protected
  232. * @param mixed $data 要操作的数据
  233. * @return boolean
  234. */
  235. protected function _facade($data) {
  236. // 检查数据字段合法性
  237. if(!empty($this->fields)) {
  238. if(!empty($this->options['field'])) {
  239. $fields = $this->options['field'];
  240. unset($this->options['field']);
  241. if(is_string($fields)) {
  242. $fields = explode(',',$fields);
  243. }
  244. }else{
  245. $fields = $this->fields;
  246. }
  247. foreach ($data as $key=>$val){
  248. if(!in_array($key,$fields,true)){
  249. if(!empty($this->options['strict'])){
  250. E(L('_DATA_TYPE_INVALID_').':['.$key.'=>'.$val.']');
  251. }
  252. unset($data[$key]);
  253. }elseif(is_scalar($val)) {
  254. // 字段类型检查 和 强制转换
  255. $this->_parseType($data,$key);
  256. }
  257. }
  258. }
  259. // 安全过滤
  260. if(!empty($this->options['filter'])) {
  261. $data = array_map($this->options['filter'],$data);
  262. unset($this->options['filter']);
  263. }
  264. $this->_before_write($data);
  265. return $data;
  266. }
  267. // 写入数据前的回调方法 包括新增和更新
  268. protected function _before_write(&$data) {}
  269. /**
  270. * 新增数据
  271. * @access public
  272. * @param mixed $data 数据
  273. * @param array $options 表达式
  274. * @param boolean $replace 是否replace
  275. * @return mixed
  276. */
  277. public function add($data='',$options=array(),$replace=false) {
  278. if(empty($data)) {
  279. // 没有传递数据,获取当前数据对象的值
  280. if(!empty($this->data)) {
  281. $data = $this->data;
  282. // 重置数据
  283. $this->data = array();
  284. }else{
  285. $this->error = L('_DATA_TYPE_INVALID_');
  286. return false;
  287. }
  288. }
  289. // 数据处理
  290. $data = $this->_facade($data);
  291. // 分析表达式
  292. $options = $this->_parseOptions($options);
  293. if(false === $this->_before_insert($data,$options)) {
  294. return false;
  295. }
  296. // 写入数据到数据库
  297. $result = $this->db->insert($data,$options,$replace);
  298. if(false !== $result && is_numeric($result)) {
  299. $pk = $this->getPk();
  300. // 增加复合主键支持
  301. if (is_array($pk)) return $result;
  302. $insertId = $this->getLastInsID();
  303. if($insertId) {
  304. // 自增主键返回插入ID
  305. $data[$pk] = $insertId;
  306. if(false === $this->_after_insert($data,$options)) {
  307. return false;
  308. }
  309. return $insertId;
  310. }
  311. if(false === $this->_after_insert($data,$options)) {
  312. return false;
  313. }
  314. }
  315. return $result;
  316. }
  317. // 插入数据前的回调方法
  318. protected function _before_insert(&$data,$options) {}
  319. // 插入成功后的回调方法
  320. protected function _after_insert($data,$options) {}
  321. public function addAll($dataList,$options=array(),$replace=false){
  322. if(empty($dataList)) {
  323. $this->error = L('_DATA_TYPE_INVALID_');
  324. return false;
  325. }
  326. // 数据处理
  327. foreach ($dataList as $key=>$data){
  328. $dataList[$key] = $this->_facade($data);
  329. }
  330. // 分析表达式
  331. $options = $this->_parseOptions($options);
  332. // 写入数据到数据库
  333. $result = $this->db->insertAll($dataList,$options,$replace);
  334. if(false !== $result ) {
  335. $insertId = $this->getLastInsID();
  336. if($insertId) {
  337. return $insertId;
  338. }
  339. }
  340. return $result;
  341. }
  342. /**
  343. * 保存数据
  344. * @access public
  345. * @param mixed $data 数据
  346. * @param array $options 表达式
  347. * @return boolean
  348. */
  349. public function save($data='',$options=array()) {
  350. if(empty($data)) {
  351. // 没有传递数据,获取当前数据对象的值
  352. if(!empty($this->data)) {
  353. $data = $this->data;
  354. // 重置数据
  355. $this->data = array();
  356. }else{
  357. $this->error = L('_DATA_TYPE_INVALID_');
  358. return false;
  359. }
  360. }
  361. // 数据处理
  362. $data = $this->_facade($data);
  363. if(empty($data)){
  364. // 没有数据则不执行
  365. $this->error = L('_DATA_TYPE_INVALID_');
  366. return false;
  367. }
  368. // 分析表达式
  369. $options = $this->_parseOptions($options);
  370. $pk = $this->getPk();
  371. if(!isset($options['where']) ) {
  372. // 如果存在主键数据 则自动作为更新条件
  373. if (is_string($pk) && isset($data[$pk])) {
  374. $where[$pk] = $data[$pk];
  375. unset($data[$pk]);
  376. } elseif (is_array($pk)) {
  377. // 增加复合主键支持
  378. foreach ($pk as $field) {
  379. if(isset($data[$field])) {
  380. $where[$field] = $data[$field];
  381. } else {
  382. // 如果缺少复合主键数据则不执行
  383. $this->error = L('_OPERATION_WRONG_');
  384. return false;
  385. }
  386. unset($data[$field]);
  387. }
  388. }
  389. if(!isset($where)){
  390. // 如果没有任何更新条件则不执行
  391. $this->error = L('_OPERATION_WRONG_');
  392. return false;
  393. }else{
  394. $options['where'] = $where;
  395. }
  396. }
  397. if(is_array($options['where']) && isset($options['where'][$pk])){
  398. $pkValue = $options['where'][$pk];
  399. }
  400. if(false === $this->_before_update($data,$options)) {
  401. return false;
  402. }
  403. $result = $this->db->update($data,$options);
  404. if(false !== $result && is_numeric($result)) {
  405. if(isset($pkValue)) $data[$pk] = $pkValue;
  406. $this->_after_update($data,$options);
  407. }
  408. return $result;
  409. }
  410. // 更新数据前的回调方法
  411. protected function _before_update(&$data,$options) {}
  412. // 更新成功后的回调方法
  413. protected function _after_update($data,$options) {}
  414. /**
  415. * 删除数据
  416. * @access public
  417. * @param mixed $options 表达式
  418. * @return mixed
  419. */
  420. public function delete($options=array()) {
  421. $pk = $this->getPk();
  422. if(empty($options) && empty($this->options['where'])) {
  423. // 如果删除条件为空 则删除当前数据对象所对应的记录
  424. if(!empty($this->data) && isset($this->data[$pk]))
  425. return $this->delete($this->data[$pk]);
  426. else
  427. return false;
  428. }
  429. if(is_numeric($options) || is_string($options)) {
  430. // 根据主键删除记录
  431. if(strpos($options,',')) {
  432. $where[$pk] = array('IN', $options);
  433. }else{
  434. $where[$pk] = $options;
  435. }
  436. $options = array();
  437. $options['where'] = $where;
  438. }
  439. // 根据复合主键删除记录
  440. if (is_array($options) && (count($options) > 0) && is_array($pk)) {
  441. $count = 0;
  442. foreach (array_keys($options) as $key) {
  443. if (is_int($key)) $count++;
  444. }
  445. if ($count == count($pk)) {
  446. $i = 0;
  447. foreach ($pk as $field) {
  448. $where[$field] = $options[$i];
  449. unset($options[$i++]);
  450. }
  451. $options['where'] = $where;
  452. } else {
  453. return false;
  454. }
  455. }
  456. // 分析表达式
  457. $options = $this->_parseOptions($options);
  458. if(empty($options['where'])){
  459. // 如果条件为空 不进行删除操作 除非设置 1=1
  460. return false;
  461. }
  462. if(is_array($options['where']) && isset($options['where'][$pk])){
  463. $pkValue = $options['where'][$pk];
  464. }
  465. if(false === $this->_before_delete($options)) {
  466. return false;
  467. }
  468. $result = $this->db->delete($options);
  469. if(false !== $result && is_numeric($result)) {
  470. $data = array();
  471. if(isset($pkValue)) $data[$pk] = $pkValue;
  472. $this->_after_delete($data,$options);
  473. }
  474. // 返回删除记录个数
  475. return $result;
  476. }
  477. // 删除数据前的回调方法
  478. protected function _before_delete($options) {}
  479. // 删除成功后的回调方法
  480. protected function _after_delete($data,$options) {}
  481. /**
  482. * 查询数据集
  483. * @access public
  484. * @param array $options 表达式参数
  485. * @return mixed
  486. */
  487. public function select($options=array()) {
  488. $pk = $this->getPk();
  489. if(is_string($options) || is_numeric($options)) {
  490. // 根据主键查询
  491. if(strpos($options,',')) {
  492. $where[$pk] = array('IN',$options);
  493. }else{
  494. $where[$pk] = $options;
  495. }
  496. $options = array();
  497. $options['where'] = $where;
  498. }elseif (is_array($options) && (count($options) > 0) && is_array($pk)) {
  499. // 根据复合主键查询
  500. $count = 0;
  501. foreach (array_keys($options) as $key) {
  502. if (is_int($key)) $count++;
  503. }
  504. if ($count == count($pk)) {
  505. $i = 0;
  506. foreach ($pk as $field) {
  507. $where[$field] = $options[$i];
  508. unset($options[$i++]);
  509. }
  510. $options['where'] = $where;
  511. } else {
  512. return false;
  513. }
  514. } elseif(false === $options){ // 用于子查询 不查询只返回SQL
  515. $options = array();
  516. // 分析表达式
  517. $options = $this->_parseOptions($options);
  518. return '( '.$this->fetchSql(true)->select($options).' )';
  519. }
  520. // 分析表达式
  521. $options = $this->_parseOptions($options);
  522. // 判断查询缓存
  523. if(isset($options['cache'])){
  524. $cache = $options['cache'];
  525. $key = is_string($cache['key'])?$cache['key']:md5(serialize($options));
  526. $data = S($key,'',$cache);
  527. if(false !== $data){
  528. return $data;
  529. }
  530. }
  531. $resultSet = $this->db->select($options);
  532. if(false === $resultSet) {
  533. return false;
  534. }
  535. if(empty($resultSet)) { // 查询结果为空
  536. return null;
  537. }
  538. if(is_string($resultSet)){
  539. return $resultSet;
  540. }
  541. $resultSet = array_map(array($this,'_read_data'),$resultSet);
  542. $this->_after_select($resultSet,$options);
  543. if(isset($options['index'])){ // 对数据集进行索引
  544. $index = explode(',',$options['index']);
  545. foreach ($resultSet as $result){
  546. $_key = $result[$index[0]];
  547. if(isset($index[1]) && isset($result[$index[1]])){
  548. $cols[$_key] = $result[$index[1]];
  549. }else{
  550. $cols[$_key] = $result;
  551. }
  552. }
  553. $resultSet = $cols;
  554. }
  555. if(isset($cache)){
  556. S($key,$resultSet,$cache);
  557. }
  558. return $resultSet;
  559. }
  560. // 查询成功后的回调方法
  561. protected function _after_select(&$resultSet,$options) {}
  562. /**
  563. * 分析表达式
  564. * @access protected
  565. * @param array $options 表达式参数
  566. * @return array
  567. */
  568. protected function _parseOptions($options=array()) {
  569. if(is_array($options))
  570. $options = array_merge($this->options,$options);
  571. if(!isset($options['table'])){
  572. // 自动获取表名
  573. $options['table'] = $this->getTableName();
  574. $fields = $this->fields;
  575. }else{
  576. // 指定数据表 则重新获取字段列表 但不支持类型检测
  577. $fields = $this->getDbFields();
  578. }
  579. // 数据表别名
  580. if(!empty($options['alias'])) {
  581. $options['table'] .= ' '.$options['alias'];
  582. }
  583. // 记录操作的模型名称
  584. $options['model'] = $this->name;
  585. // 字段类型验证
  586. if(isset($options['where']) && is_array($options['where']) && !empty($fields) && !isset($options['join'])) {
  587. // 对数组查询条件进行字段类型检查
  588. foreach ($options['where'] as $key=>$val){
  589. $key = trim($key);
  590. if(in_array($key,$fields,true)){
  591. if(is_scalar($val)) {
  592. $this->_parseType($options['where'],$key);
  593. }
  594. }elseif(!is_numeric($key) && '_' != substr($key,0,1) && false === strpos($key,'.') && false === strpos($key,'(') && false === strpos($key,'|') && false === strpos($key,'&')){
  595. if(!empty($this->options['strict'])){
  596. E(L('_ERROR_QUERY_EXPRESS_').':['.$key.'=>'.$val.']');
  597. }
  598. unset($options['where'][$key]);
  599. }
  600. }
  601. }
  602. // 查询过后清空sql表达式组装 避免影响下次查询
  603. $this->options = array();
  604. // 表达式过滤
  605. $this->_options_filter($options);
  606. return $options;
  607. }
  608. // 表达式过滤回调方法
  609. protected function _options_filter(&$options) {}
  610. /**
  611. * 数据类型检测
  612. * @access protected
  613. * @param mixed $data 数据
  614. * @param string $key 字段名
  615. * @return void
  616. */
  617. protected function _parseType(&$data,$key) {
  618. if(!isset($this->options['bind'][':'.$key]) && isset($this->fields['_type'][$key])){
  619. $fieldType = strtolower($this->fields['_type'][$key]);
  620. if(false !== strpos($fieldType,'enum')){
  621. // 支持ENUM类型优先检测
  622. }elseif(false === strpos($fieldType,'bigint') && false !== strpos($fieldType,'int')) {
  623. $data[$key] = intval($data[$key]);
  624. }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){
  625. $data[$key] = floatval($data[$key]);
  626. }elseif(false !== strpos($fieldType,'bool')){
  627. $data[$key] = (bool)$data[$key];
  628. }
  629. }
  630. }
  631. /**
  632. * 数据读取后的处理
  633. * @access protected
  634. * @param array $data 当前数据
  635. * @return array
  636. */
  637. protected function _read_data($data) {
  638. // 检查字段映射
  639. if(!empty($this->_map) && C('READ_DATA_MAP')) {
  640. foreach ($this->_map as $key=>$val){
  641. if(isset($data[$val])) {
  642. $data[$key] = $data[$val];
  643. unset($data[$val]);
  644. }
  645. }
  646. }
  647. return $data;
  648. }
  649. /**
  650. * 查询数据
  651. * @access public
  652. * @param mixed $options 表达式参数
  653. * @return mixed
  654. */
  655. public function find($options=array()) {
  656. if(is_numeric($options) || is_string($options)) {
  657. $where[$this->getPk()] = $options;
  658. $options = array();
  659. $options['where'] = $where;
  660. }
  661. // 根据复合主键查找记录
  662. $pk = $this->getPk();
  663. if (is_array($options) && (count($options) > 0) && is_array($pk)) {
  664. // 根据复合主键查询
  665. $count = 0;
  666. foreach (array_keys($options) as $key) {
  667. if (is_int($key)) $count++;
  668. }
  669. if ($count == count($pk)) {
  670. $i = 0;
  671. foreach ($pk as $field) {
  672. $where[$field] = $options[$i];
  673. unset($options[$i++]);
  674. }
  675. $options['where'] = $where;
  676. } else {
  677. return false;
  678. }
  679. }
  680. // 总是查找一条记录
  681. $options['limit'] = 1;
  682. // 分析表达式
  683. $options = $this->_parseOptions($options);
  684. // 判断查询缓存
  685. if(isset($options['cache'])){
  686. $cache = $options['cache'];
  687. $key = is_string($cache['key'])?$cache['key']:md5(serialize($options));
  688. $data = S($key,'',$cache);
  689. if(false !== $data){
  690. $this->data = $data;
  691. return $data;
  692. }
  693. }
  694. $resultSet = $this->db->select($options);
  695. if(false === $resultSet) {
  696. return false;
  697. }
  698. if(empty($resultSet)) {// 查询结果为空
  699. return null;
  700. }
  701. if(is_string($resultSet)){
  702. return $resultSet;
  703. }
  704. // 读取数据后的处理
  705. $data = $this->_read_data($resultSet[0]);
  706. $this->_after_find($data,$options);
  707. $this->data = $data;
  708. if(isset($cache)){
  709. S($key,$data,$cache);
  710. }
  711. return $this->data;
  712. }
  713. // 查询成功的回调方法
  714. protected function _after_find(&$result,$options) {}
  715. /**
  716. * 设置记录的某个字段值
  717. * 支持使用数据库字段和方法
  718. * @access public
  719. * @param string|array $field 字段名
  720. * @param string $value 字段值
  721. * @return boolean
  722. */
  723. public function setField($field,$value='') {
  724. if(is_array($field)) {
  725. $data = $field;
  726. }else{
  727. $data[$field] = $value;
  728. }
  729. return $this->save($data);
  730. }
  731. /**
  732. * 字段值增长
  733. * @access public
  734. * @param string $field 字段名
  735. * @param integer $step 增长值
  736. * @param integer $lazyTime 延时时间(s)
  737. * @return boolean
  738. */
  739. public function setInc($field,$step=1) {
  740. return $this->setField($field,array('exp',$field.'+'.$step));
  741. }
  742. /**
  743. * 字段值减少
  744. * @access public
  745. * @param string $field 字段名
  746. * @param integer $step 减少值
  747. * @param integer $lazyTime 延时时间(s)
  748. * @return boolean
  749. */
  750. public function setDec($field,$step=1) {
  751. return $this->setField($field,array('exp',$field.'-'.$step));
  752. }
  753. /**
  754. * 获取一条记录的某个字段值
  755. * @access public
  756. * @param string $field 字段名
  757. * @param string $spea 字段数据间隔符号 NULL返回数组
  758. * @return mixed
  759. */
  760. public function getField($field,$sepa=null) {
  761. $options['field'] = $field;
  762. $options = $this->_parseOptions($options);
  763. // 判断查询缓存
  764. if(isset($options['cache'])){
  765. $cache = $options['cache'];
  766. $key = is_string($cache['key'])?$cache['key']:md5($sepa.serialize($options));
  767. $data = S($key,'',$cache);
  768. if(false !== $data){
  769. return $data;
  770. }
  771. }
  772. $field = trim($field);
  773. if(strpos($field,',') && false !== $sepa) { // 多字段
  774. if(!isset($options['limit'])){
  775. $options['limit'] = is_numeric($sepa)?$sepa:'';
  776. }
  777. $resultSet = $this->db->select($options);
  778. if(!empty($resultSet)) {
  779. $_field = explode(',', $field);
  780. $field = array_keys($resultSet[0]);
  781. $key1 = array_shift($field);
  782. $key2 = array_shift($field);
  783. $cols = array();
  784. $count = count($_field);
  785. foreach ($resultSet as $result){
  786. $name = $result[$key1];
  787. if(2==$count) {
  788. $cols[$name] = $result[$key2];
  789. }else{
  790. $cols[$name] = is_string($sepa)?implode($sepa,array_slice($result,1)):$result;
  791. }
  792. }
  793. if(isset($cache)){
  794. S($key,$cols,$cache);
  795. }
  796. return $cols;
  797. }
  798. }else{ // 查找一条记录
  799. // 返回数据个数
  800. if(true !== $sepa) {// 当sepa指定为true的时候 返回所有数据
  801. $options['limit'] = is_numeric($sepa)?$sepa:1;
  802. }
  803. $result = $this->db->select($options);
  804. if(!empty($result)) {
  805. if(true !== $sepa && 1==$options['limit']) {
  806. $data = reset($result[0]);
  807. if(isset($cache)){
  808. S($key,$data,$cache);
  809. }
  810. return $data;
  811. }
  812. foreach ($result as $val){
  813. $array[] = $val[$field];
  814. }
  815. if(isset($cache)){
  816. S($key,$array,$cache);
  817. }
  818. return $array;
  819. }
  820. }
  821. return null;
  822. }
  823. /**
  824. * 创建数据对象 但不保存到数据库
  825. * @access public
  826. * @param mixed $data 创建数据
  827. * @return mixed
  828. */
  829. public function create($data='') {
  830. // 如果没有传值默认取POST数据
  831. if(empty($data)) {
  832. $data = I('post.');
  833. }elseif(is_object($data)){
  834. $data = get_object_vars($data);
  835. }
  836. // 验证数据
  837. if(empty($data) || !is_array($data)) {
  838. $this->error = L('_DATA_TYPE_INVALID_');
  839. return false;
  840. }
  841. // 检测提交字段的合法性
  842. if(isset($this->options['field'])) { // $this->field('field1,field2...')->create()
  843. $fields = $this->options['field'];
  844. unset($this->options['field']);
  845. }
  846. if(isset($fields)) {
  847. if(is_string($fields)) {
  848. $fields = explode(',',$fields);
  849. }
  850. }
  851. // 验证完成生成数据对象
  852. if($this->autoCheckFields) { // 开启字段检测 则过滤非法字段数据
  853. $fields = $this->getDbFields();
  854. foreach ($data as $key=>$val){
  855. if(!in_array($key,$fields)) {
  856. unset($data[$key]);
  857. }elseif(MAGIC_QUOTES_GPC && is_string($val)){
  858. $data[$key] = stripslashes($val);
  859. }
  860. }
  861. }
  862. // 赋值当前数据对象
  863. $this->data = $data;
  864. // 返回创建的数据以供其他调用
  865. return $data;
  866. }
  867. /**
  868. * 使用正则验证数据
  869. * @access public
  870. * @param string $value 要验证的数据
  871. * @param string $rule 验证规则
  872. * @return boolean
  873. */
  874. public function regex($value,$rule) {
  875. $validate = array(
  876. 'require' => '/\S+/',
  877. 'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
  878. 'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(:\d+)?(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
  879. 'currency' => '/^\d+(\.\d+)?$/',
  880. 'number' => '/^\d+$/',
  881. 'zip' => '/^\d{6}$/',
  882. 'integer' => '/^[-\+]?\d+$/',
  883. 'double' => '/^[-\+]?\d+(\.\d+)?$/',
  884. 'english' => '/^[A-Za-z]+$/',
  885. 'chinese' => '/^[\x{4e00}-\x{9fa5}]+$/u',
  886. );
  887. // 检查是否有内置的正则表达式
  888. if(isset($validate[strtolower($rule)]))
  889. $rule = $validate[strtolower($rule)];
  890. return preg_match($rule,$value)===1;
  891. }
  892. /**
  893. * 验证数据 支持 in between equal length regex expire ip_allow ip_deny
  894. * @access public
  895. * @param string $value 验证数据
  896. * @param mixed $rule 验证表达式
  897. * @param string $type 验证方式 默认为正则验证
  898. * @return boolean
  899. */
  900. public function check($value,$rule,$type='regex'){
  901. $type = strtolower(trim($type));
  902. switch($type) {
  903. case 'in': // 验证是否在某个指定范围之内 逗号分隔字符串或者数组
  904. case 'notin':
  905. $range = is_array($rule)? $rule : explode(',',$rule);
  906. return $type == 'in' ? in_array($value ,$range) : !in_array($value ,$range);
  907. case 'between': // 验证是否在某个范围
  908. case 'notbetween': // 验证是否不在某个范围
  909. if (is_array($rule)){
  910. $min = $rule[0];
  911. $max = $rule[1];
  912. }else{
  913. list($min,$max) = explode(',',$rule);
  914. }
  915. return $type == 'between' ? $value>=$min && $value<=$max : $value<$min || $value>$max;
  916. case 'equal': // 验证是否等于某个值
  917. case 'notequal': // 验证是否等于某个值
  918. return $type == 'equal' ? $value == $rule : $value != $rule;
  919. case 'length': // 验证长度
  920. $length = mb_strlen($value,'utf-8'); // 当前数据长度
  921. if(strpos($rule,',')) { // 长度区间
  922. list($min,$max) = explode(',',$rule);
  923. return $length >= $min && $length <= $max;
  924. }else{// 指定长度
  925. return $length == $rule;
  926. }
  927. case 'expire':
  928. list($start,$end) = explode(',',$rule);
  929. if(!is_numeric($start)) $start = strtotime($start);
  930. if(!is_numeric($end)) $end = strtotime($end);
  931. return NOW_TIME >= $start && NOW_TIME <= $end;
  932. case 'ip_allow': // IP 操作许可验证
  933. return in_array(get_client_ip(),explode(',',$rule));
  934. case 'ip_deny': // IP 操作禁止验证
  935. return !in_array(get_client_ip(),explode(',',$rule));
  936. case 'regex':
  937. default: // 默认使用正则验证 可以使用验证类中定义的验证名称
  938. // 检查附加规则
  939. return $this->regex($value,$rule);
  940. }
  941. }
  942. /**
  943. * SQL查询
  944. * @access public
  945. * @param string $sql SQL指令
  946. * @return mixed
  947. */
  948. public function query($sql) {
  949. return $this->db->query($sql);
  950. }
  951. /**
  952. * 执行SQL语句
  953. * @access public
  954. * @param string $sql SQL指令
  955. * @return false | integer
  956. */
  957. public function execute($sql) {
  958. return $this->db->execute($sql);
  959. }
  960. /**
  961. * 切换当前的数据库连接
  962. * @access public
  963. * @param integer $linkNum 连接序号
  964. * @param mixed $config 数据库连接信息
  965. * @param boolean $force 强制重新连接
  966. * @return Model
  967. */
  968. public function db($linkNum='',$config='',$force=false) {
  969. if('' === $linkNum && $this->db) {
  970. return $this->db;
  971. }
  972. if(!isset($this->_db[$linkNum]) || $force ) {
  973. // 创建一个新的实例
  974. if(!empty($config) && is_string($config) && false === strpos($config,'/')) { // 支持读取配置参数
  975. $config = C($config);
  976. }
  977. $this->_db[$linkNum] = Db::getInstance($config);
  978. }elseif(NULL === $config){
  979. $this->_db[$linkNum]->close(); // 关闭数据库连接
  980. unset($this->_db[$linkNum]);
  981. return ;
  982. }
  983. // 切换数据库连接
  984. $this->db = $this->_db[$linkNum];
  985. $this->_after_db();
  986. // 字段检测
  987. if(!empty($this->name) && $this->autoCheckFields) $this->_checkTableInfo();
  988. return $this;
  989. }
  990. // 数据库切换后回调方法
  991. protected function _after_db() {}
  992. /**
  993. * 得到当前的数据对象名称
  994. * @access public
  995. * @return string
  996. */
  997. public function getModelName() {
  998. if(empty($this->name)){
  999. $name = substr(get_class($this),0,-strlen(C('DEFAULT_M_LAYER')));
  1000. if ( $pos = strrpos($name,'\\') ) {//有命名空间
  1001. $this->name = substr($name,$pos+1);
  1002. }else{
  1003. $this->name = $name;
  1004. }
  1005. }
  1006. return $this->name;
  1007. }
  1008. /**
  1009. * 得到完整的数据表名
  1010. * @access public
  1011. * @return string
  1012. */
  1013. public function getTableName() {
  1014. if(empty($this->trueTableName)) {
  1015. $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
  1016. if(!empty($this->tableName)) {
  1017. $tableName .= $this->tableName;
  1018. }else{
  1019. $tableName .= parse_name($this->name);
  1020. }
  1021. $this->trueTableName = strtolower($tableName);
  1022. }
  1023. return (!empty($this->dbName)?$this->dbName.'.':'').$this->trueTableName;
  1024. }
  1025. /**
  1026. * 启动事务
  1027. * @access public
  1028. * @return void
  1029. */
  1030. public function startTrans() {
  1031. $this->commit();
  1032. $this->db->startTrans();
  1033. return ;
  1034. }
  1035. /**
  1036. * 提交事务
  1037. * @access public
  1038. * @return boolean
  1039. */
  1040. public function commit() {
  1041. return $this->db->commit();
  1042. }
  1043. /**
  1044. * 事务回滚
  1045. * @access public
  1046. * @return boolean
  1047. */
  1048. public function rollback() {
  1049. return $this->db->rollback();
  1050. }
  1051. /**
  1052. * 返回模型的错误信息
  1053. * @access public
  1054. * @return string
  1055. */
  1056. public function getError(){
  1057. return $this->error;
  1058. }
  1059. /**
  1060. * 返回数据库的错误信息
  1061. * @access public
  1062. * @return string
  1063. */
  1064. public function getDbError() {
  1065. return $this->db->getError();
  1066. }
  1067. /**
  1068. * 返回最后插入的ID
  1069. * @access public
  1070. * @return string
  1071. */
  1072. public function getLastInsID() {
  1073. return $this->db->getLastInsID();
  1074. }
  1075. /**
  1076. * 返回最后执行的sql语句
  1077. * @access public
  1078. * @return string
  1079. */
  1080. public function getLastSql() {
  1081. return $this->db->getLastSql($this->name);
  1082. }
  1083. // 鉴于getLastSql比较常用 增加_sql 别名
  1084. public function _sql(){
  1085. return $this->getLastSql();
  1086. }
  1087. /**
  1088. * 获取主键名称
  1089. * @access public
  1090. * @return string
  1091. */
  1092. public function getPk() {
  1093. return $this->pk;
  1094. }
  1095. /**
  1096. * 获取数据表字段信息
  1097. * @access public
  1098. * @return array
  1099. */
  1100. public function getDbFields(){
  1101. if(isset($this->options['table'])) {// 动态指定表名
  1102. if(is_array($this->options['table'])){
  1103. $table = key($this->options['table']);
  1104. }else{
  1105. $table = $this->options['table'];
  1106. }
  1107. $fields = $this->db->getFields($table);
  1108. return $fields ? array_keys($fields) : false;
  1109. }
  1110. if($this->fields) {
  1111. $fields = $this->fields;
  1112. unset($fields['_type'],$fields['_pk']);
  1113. return $fields;
  1114. }
  1115. return false;
  1116. }
  1117. /**
  1118. * 设置数据对象值
  1119. * @access public
  1120. * @param mixed $data 数据
  1121. * @return Model
  1122. */
  1123. public function data($data=''){
  1124. if('' === $data && !empty($this->data)) {
  1125. return $this->data;
  1126. }
  1127. if(is_object($data)){
  1128. $data = get_object_vars($data);
  1129. }elseif(is_string($data)){
  1130. parse_str($data,$data);
  1131. }elseif(!is_array($data)){
  1132. E(L('_DATA_TYPE_INVALID_'));
  1133. }
  1134. $this->data = $data;
  1135. return $this;
  1136. }
  1137. /**
  1138. * 指定当前的数据表
  1139. * @access public
  1140. * @param mixed $table
  1141. * @return Model
  1142. */
  1143. public function table($table) {
  1144. $prefix = $this->tablePrefix;
  1145. if(is_array($table)) {
  1146. $this->options['table'] = $table;
  1147. }elseif(!empty($table)) {
  1148. //将__TABLE_NAME__替换成带前缀的表名
  1149. $table = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $table);
  1150. $this->options['table'] = $table;
  1151. }
  1152. return $this;
  1153. }
  1154. /**
  1155. * USING支持 用于多表删除
  1156. * @access public
  1157. * @param mixed $using
  1158. * @return Model
  1159. */
  1160. public function using($using){
  1161. $prefix = $this->tablePrefix;
  1162. if(is_array($using)) {
  1163. $this->options['using'] = $using;
  1164. }elseif(!empty($using)) {
  1165. //将__TABLE_NAME__替换成带前缀的表名
  1166. $using = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $using);
  1167. $this->options['using'] = $using;
  1168. }
  1169. return $this;
  1170. }
  1171. /**
  1172. * 查询SQL组装 join
  1173. * @access public
  1174. * @param mixed $join
  1175. * @param string $type JOIN类型
  1176. * @return Model
  1177. */
  1178. public function join($join,$type='INNER') {
  1179. $prefix = $this->tablePrefix;
  1180. if(is_array($join)) {
  1181. foreach ($join as $key=>&$_join){
  1182. $_join = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $_join);
  1183. $_join = false !== stripos($_join,'JOIN')? $_join : $type.' JOIN ' .$_join;
  1184. }
  1185. $this->options['join'] = $join;
  1186. }elseif(!empty($join)) {
  1187. //将__TABLE_NAME__字符串替换成带前缀的表名
  1188. $join = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $join);
  1189. $this->options['join'][] = false !== stripos($join,'JOIN')? $join : $type.' JOIN '.$join;
  1190. }
  1191. return $this;
  1192. }
  1193. /**
  1194. * 查询SQL组装 union
  1195. * @access public
  1196. * @param mixed $union
  1197. * @param boolean $all
  1198. * @return Model
  1199. */
  1200. public function union($union,$all=false) {
  1201. if(empty($union)) return $this;
  1202. if($all) {
  1203. $this->options['union']['_all'] = true;
  1204. }
  1205. if(is_object($union)) {
  1206. $union = get_object_vars($union);
  1207. }
  1208. // 转换union表达式
  1209. if(is_string($union) ) {
  1210. $prefix = $this->tablePrefix;
  1211. //将__TABLE_NAME__字符串替换成带前缀的表名
  1212. $options = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $union);
  1213. }elseif(is_array($union)){
  1214. if(isset($union[0])) {
  1215. $this->options['union'] = array_merge($this->options['union'],$union);
  1216. return $this;
  1217. }else{
  1218. $options = $union;
  1219. }
  1220. }else{
  1221. E(L('_DATA_TYPE_INVALID_'));
  1222. }
  1223. $this->options['union'][] = $options;
  1224. return $this;
  1225. }
  1226. /**
  1227. * 查询缓存
  1228. * @access public
  1229. * @param mixed $key
  1230. * @param integer $expire
  1231. * @param string $type
  1232. * @return Model
  1233. */
  1234. public function cache($key=true,$expire=null,$type=''){
  1235. // 增加快捷调用方式 cache(10) 等同于 cache(true, 10)
  1236. if(is_numeric($key) && is_null($expire)){
  1237. $expire = $key;
  1238. $key = true;
  1239. }
  1240. if(false !== $key)
  1241. $this->options['cache'] = array('key'=>$key,'expire'=>$expire,'type'=>$type);
  1242. return $this;
  1243. }
  1244. /**
  1245. * 指定查询字段 支持字段排除
  1246. * @access public
  1247. * @param mixed $field
  1248. * @param boolean $except 是否排除
  1249. * @return Model
  1250. */
  1251. public function field($field,$except=false){
  1252. if(true === $field) {// 获取全部字段
  1253. $fields = $this->getDbFields();
  1254. $field = $fields?:'*';
  1255. }elseif($except) {// 字段排除
  1256. if(is_string($field)) {
  1257. $field = explode(',',$field);
  1258. }
  1259. $fields = $this->getDbFields();
  1260. $field = $fields?array_diff($fields,$field):$field;
  1261. }
  1262. $this->options['field'] = $field;
  1263. return $this;
  1264. }
  1265. /**
  1266. * 调用命名范围
  1267. * @access public
  1268. * @param mixed $scope 命名范围名称 支持多个 和直接定义
  1269. * @param array $args 参数
  1270. * @return Model
  1271. */
  1272. public function scope($scope='',$args=NULL){
  1273. if('' === $scope) {
  1274. if(isset($this->_scope['default'])) {
  1275. // 默认的命名范围
  1276. $options = $this->_scope['default'];
  1277. }else{
  1278. return $this;
  1279. }
  1280. }elseif(is_string($scope)){ // 支持多个命名范围调用 用逗号分割
  1281. $scopes = explode(',',$scope);
  1282. $options = array();
  1283. foreach ($scopes as $name){
  1284. if(!isset($this->_scope[$name])) continue;
  1285. $options = array_merge($options,$this->_scope[$name]);
  1286. }
  1287. if(!empty($args) && is_array($args)) {
  1288. $options = array_merge($options,$args);
  1289. }
  1290. }elseif(is_array($scope)){ // 直接传入命名范围定义
  1291. $options = $scope;
  1292. }
  1293. if(is_array($options) && !empty($options)){
  1294. $this->options = array_merge($this->options,array_change_key_case($options));
  1295. }
  1296. return $this;
  1297. }
  1298. /**
  1299. * 指定查询条件 支持安全过滤
  1300. * @access public
  1301. * @param mixed $where 条件表达式
  1302. * @param mixed $parse 预处理参数
  1303. * @return Model
  1304. */
  1305. public function where($where,$parse=null){
  1306. if(!is_null($parse) && is_string($where)) {
  1307. if(!is_array($parse)) {
  1308. $parse = func_get_args();
  1309. array_shift($parse);
  1310. }
  1311. $parse = array_map(array($this->db,'escapeString'),$parse);
  1312. $where = vsprintf($where,$parse);
  1313. }elseif(is_object($where)){
  1314. $where = get_object_vars($where);
  1315. }
  1316. if(is_string($where) && '' != $where){
  1317. $map = array();
  1318. $map['_string'] = $where;
  1319. $where = $map;
  1320. }
  1321. if(isset($this->options['where'])){
  1322. $this->options['where'] = array_merge($this->options['where'],$where);
  1323. }else{
  1324. $this->options['where'] = $where;
  1325. }
  1326. return $this;
  1327. }
  1328. /**
  1329. * 指定查询数量
  1330. * @access public
  1331. * @param mixed $offset 起始位置
  1332. * @param mixed $length 查询数量
  1333. * @return Model
  1334. */
  1335. public function limit($offset,$length=null){
  1336. if(is_null($length) && strpos($offset,',')){
  1337. list($offset,$length) = explode(',',$offset);
  1338. }
  1339. $this->options['limit'] = intval($offset).( $length? ','.intval($length) : '' );
  1340. return $this;
  1341. }
  1342. /**
  1343. * 指定分页
  1344. * @access public
  1345. * @param mixed $page 页数
  1346. * @param mixed $listRows 每页数量
  1347. * @return Model
  1348. */
  1349. public function page($page,$listRows=null){
  1350. if(is_null($listRows) && strpos($page,',')){
  1351. list($page,$listRows) = explode(',',$page);
  1352. }
  1353. $this->options['page'] = array(intval($page),intval($listRows));
  1354. return $this;
  1355. }
  1356. /**
  1357. * 查询注释
  1358. * @access public
  1359. * @param string $comment 注释
  1360. * @return Model
  1361. */
  1362. public function comment($comment){
  1363. $this->options['comment'] = $comment;
  1364. return $this;
  1365. }
  1366. /**
  1367. * 获取执行的SQL语句
  1368. * @access public
  1369. * @param boolean $fetch 是否返回sql
  1370. * @return Model
  1371. */
  1372. public function fetchSql($fetch){
  1373. $this->options['fetch_sql'] = $fetch;
  1374. return $this;
  1375. }
  1376. /**
  1377. * 参数绑定
  1378. * @access public
  1379. * @param string $key 参数名
  1380. * @param mixed $value 绑定的变量及绑定参数
  1381. * @return Model
  1382. */
  1383. public function bind($key,$value=false) {
  1384. if(is_array($key)){
  1385. $this->options['bind'] = $key;
  1386. }else{
  1387. $num = func_num_args();
  1388. if($num>2){
  1389. $params = func_get_args();
  1390. array_shift($params);
  1391. $this->options['bind'][$key] = $params;
  1392. }else{
  1393. $this->options['bind'][$key] = $value;
  1394. }
  1395. }
  1396. return $this;
  1397. }
  1398. /**
  1399. * 设置模型的属性值
  1400. * @access public
  1401. * @param string $name 名称
  1402. * @param mixed $value 值
  1403. * @return Model
  1404. */
  1405. public function setProperty($name,$value) {
  1406. if(property_exists($this,$name))
  1407. $this->$name = $value;
  1408. return $this;
  1409. }
  1410. }