Model.class.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  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. );
  886. // 检查是否有内置的正则表达式
  887. if(isset($validate[strtolower($rule)]))
  888. $rule = $validate[strtolower($rule)];
  889. return preg_match($rule,$value)===1;
  890. }
  891. /**
  892. * 验证数据 支持 in between equal length regex expire ip_allow ip_deny
  893. * @access public
  894. * @param string $value 验证数据
  895. * @param mixed $rule 验证表达式
  896. * @param string $type 验证方式 默认为正则验证
  897. * @return boolean
  898. */
  899. public function check($value,$rule,$type='regex'){
  900. $type = strtolower(trim($type));
  901. switch($type) {
  902. case 'in': // 验证是否在某个指定范围之内 逗号分隔字符串或者数组
  903. case 'notin':
  904. $range = is_array($rule)? $rule : explode(',',$rule);
  905. return $type == 'in' ? in_array($value ,$range) : !in_array($value ,$range);
  906. case 'between': // 验证是否在某个范围
  907. case 'notbetween': // 验证是否不在某个范围
  908. if (is_array($rule)){
  909. $min = $rule[0];
  910. $max = $rule[1];
  911. }else{
  912. list($min,$max) = explode(',',$rule);
  913. }
  914. return $type == 'between' ? $value>=$min && $value<=$max : $value<$min || $value>$max;
  915. case 'equal': // 验证是否等于某个值
  916. case 'notequal': // 验证是否等于某个值
  917. return $type == 'equal' ? $value == $rule : $value != $rule;
  918. case 'length': // 验证长度
  919. $length = mb_strlen($value,'utf-8'); // 当前数据长度
  920. if(strpos($rule,',')) { // 长度区间
  921. list($min,$max) = explode(',',$rule);
  922. return $length >= $min && $length <= $max;
  923. }else{// 指定长度
  924. return $length == $rule;
  925. }
  926. case 'expire':
  927. list($start,$end) = explode(',',$rule);
  928. if(!is_numeric($start)) $start = strtotime($start);
  929. if(!is_numeric($end)) $end = strtotime($end);
  930. return NOW_TIME >= $start && NOW_TIME <= $end;
  931. case 'ip_allow': // IP 操作许可验证
  932. return in_array(get_client_ip(),explode(',',$rule));
  933. case 'ip_deny': // IP 操作禁止验证
  934. return !in_array(get_client_ip(),explode(',',$rule));
  935. case 'regex':
  936. default: // 默认使用正则验证 可以使用验证类中定义的验证名称
  937. // 检查附加规则
  938. return $this->regex($value,$rule);
  939. }
  940. }
  941. /**
  942. * SQL查询
  943. * @access public
  944. * @param string $sql SQL指令
  945. * @return mixed
  946. */
  947. public function query($sql) {
  948. return $this->db->query($sql);
  949. }
  950. /**
  951. * 执行SQL语句
  952. * @access public
  953. * @param string $sql SQL指令
  954. * @return false | integer
  955. */
  956. public function execute($sql) {
  957. return $this->db->execute($sql);
  958. }
  959. /**
  960. * 切换当前的数据库连接
  961. * @access public
  962. * @param integer $linkNum 连接序号
  963. * @param mixed $config 数据库连接信息
  964. * @param boolean $force 强制重新连接
  965. * @return Model
  966. */
  967. public function db($linkNum='',$config='',$force=false) {
  968. if('' === $linkNum && $this->db) {
  969. return $this->db;
  970. }
  971. if(!isset($this->_db[$linkNum]) || $force ) {
  972. // 创建一个新的实例
  973. if(!empty($config) && is_string($config) && false === strpos($config,'/')) { // 支持读取配置参数
  974. $config = C($config);
  975. }
  976. $this->_db[$linkNum] = Db::getInstance($config);
  977. }elseif(NULL === $config){
  978. $this->_db[$linkNum]->close(); // 关闭数据库连接
  979. unset($this->_db[$linkNum]);
  980. return ;
  981. }
  982. // 切换数据库连接
  983. $this->db = $this->_db[$linkNum];
  984. $this->_after_db();
  985. // 字段检测
  986. if(!empty($this->name) && $this->autoCheckFields) $this->_checkTableInfo();
  987. return $this;
  988. }
  989. // 数据库切换后回调方法
  990. protected function _after_db() {}
  991. /**
  992. * 得到当前的数据对象名称
  993. * @access public
  994. * @return string
  995. */
  996. public function getModelName() {
  997. if(empty($this->name)){
  998. $name = substr(get_class($this),0,-strlen(C('DEFAULT_M_LAYER')));
  999. if ( $pos = strrpos($name,'\\') ) {//有命名空间
  1000. $this->name = substr($name,$pos+1);
  1001. }else{
  1002. $this->name = $name;
  1003. }
  1004. }
  1005. return $this->name;
  1006. }
  1007. /**
  1008. * 得到完整的数据表名
  1009. * @access public
  1010. * @return string
  1011. */
  1012. public function getTableName() {
  1013. if(empty($this->trueTableName)) {
  1014. $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
  1015. if(!empty($this->tableName)) {
  1016. $tableName .= $this->tableName;
  1017. }else{
  1018. $tableName .= parse_name($this->name);
  1019. }
  1020. $this->trueTableName = strtolower($tableName);
  1021. }
  1022. return (!empty($this->dbName)?$this->dbName.'.':'').$this->trueTableName;
  1023. }
  1024. /**
  1025. * 启动事务
  1026. * @access public
  1027. * @return void
  1028. */
  1029. public function startTrans() {
  1030. $this->commit();
  1031. $this->db->startTrans();
  1032. return ;
  1033. }
  1034. /**
  1035. * 提交事务
  1036. * @access public
  1037. * @return boolean
  1038. */
  1039. public function commit() {
  1040. return $this->db->commit();
  1041. }
  1042. /**
  1043. * 事务回滚
  1044. * @access public
  1045. * @return boolean
  1046. */
  1047. public function rollback() {
  1048. return $this->db->rollback();
  1049. }
  1050. /**
  1051. * 返回模型的错误信息
  1052. * @access public
  1053. * @return string
  1054. */
  1055. public function getError(){
  1056. return $this->error;
  1057. }
  1058. /**
  1059. * 返回数据库的错误信息
  1060. * @access public
  1061. * @return string
  1062. */
  1063. public function getDbError() {
  1064. return $this->db->getError();
  1065. }
  1066. /**
  1067. * 返回最后插入的ID
  1068. * @access public
  1069. * @return string
  1070. */
  1071. public function getLastInsID() {
  1072. return $this->db->getLastInsID();
  1073. }
  1074. /**
  1075. * 返回最后执行的sql语句
  1076. * @access public
  1077. * @return string
  1078. */
  1079. public function getLastSql() {
  1080. return $this->db->getLastSql($this->name);
  1081. }
  1082. // 鉴于getLastSql比较常用 增加_sql 别名
  1083. public function _sql(){
  1084. return $this->getLastSql();
  1085. }
  1086. /**
  1087. * 获取主键名称
  1088. * @access public
  1089. * @return string
  1090. */
  1091. public function getPk() {
  1092. return $this->pk;
  1093. }
  1094. /**
  1095. * 获取数据表字段信息
  1096. * @access public
  1097. * @return array
  1098. */
  1099. public function getDbFields(){
  1100. if(isset($this->options['table'])) {// 动态指定表名
  1101. if(is_array($this->options['table'])){
  1102. $table = key($this->options['table']);
  1103. }else{
  1104. $table = $this->options['table'];
  1105. }
  1106. $fields = $this->db->getFields($table);
  1107. return $fields ? array_keys($fields) : false;
  1108. }
  1109. if($this->fields) {
  1110. $fields = $this->fields;
  1111. unset($fields['_type'],$fields['_pk']);
  1112. return $fields;
  1113. }
  1114. return false;
  1115. }
  1116. /**
  1117. * 设置数据对象值
  1118. * @access public
  1119. * @param mixed $data 数据
  1120. * @return Model
  1121. */
  1122. public function data($data=''){
  1123. if('' === $data && !empty($this->data)) {
  1124. return $this->data;
  1125. }
  1126. if(is_object($data)){
  1127. $data = get_object_vars($data);
  1128. }elseif(is_string($data)){
  1129. parse_str($data,$data);
  1130. }elseif(!is_array($data)){
  1131. E(L('_DATA_TYPE_INVALID_'));
  1132. }
  1133. $this->data = $data;
  1134. return $this;
  1135. }
  1136. /**
  1137. * 指定当前的数据表
  1138. * @access public
  1139. * @param mixed $table
  1140. * @return Model
  1141. */
  1142. public function table($table) {
  1143. $prefix = $this->tablePrefix;
  1144. if(is_array($table)) {
  1145. $this->options['table'] = $table;
  1146. }elseif(!empty($table)) {
  1147. //将__TABLE_NAME__替换成带前缀的表名
  1148. $table = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $table);
  1149. $this->options['table'] = $table;
  1150. }
  1151. return $this;
  1152. }
  1153. /**
  1154. * USING支持 用于多表删除
  1155. * @access public
  1156. * @param mixed $using
  1157. * @return Model
  1158. */
  1159. public function using($using){
  1160. $prefix = $this->tablePrefix;
  1161. if(is_array($using)) {
  1162. $this->options['using'] = $using;
  1163. }elseif(!empty($using)) {
  1164. //将__TABLE_NAME__替换成带前缀的表名
  1165. $using = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $using);
  1166. $this->options['using'] = $using;
  1167. }
  1168. return $this;
  1169. }
  1170. /**
  1171. * 查询SQL组装 join
  1172. * @access public
  1173. * @param mixed $join
  1174. * @param string $type JOIN类型
  1175. * @return Model
  1176. */
  1177. public function join($join,$type='INNER') {
  1178. $prefix = $this->tablePrefix;
  1179. if(is_array($join)) {
  1180. foreach ($join as $key=>&$_join){
  1181. $_join = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $_join);
  1182. $_join = false !== stripos($_join,'JOIN')? $_join : $type.' JOIN ' .$_join;
  1183. }
  1184. $this->options['join'] = $join;
  1185. }elseif(!empty($join)) {
  1186. //将__TABLE_NAME__字符串替换成带前缀的表名
  1187. $join = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $join);
  1188. $this->options['join'][] = false !== stripos($join,'JOIN')? $join : $type.' JOIN '.$join;
  1189. }
  1190. return $this;
  1191. }
  1192. /**
  1193. * 查询SQL组装 union
  1194. * @access public
  1195. * @param mixed $union
  1196. * @param boolean $all
  1197. * @return Model
  1198. */
  1199. public function union($union,$all=false) {
  1200. if(empty($union)) return $this;
  1201. if($all) {
  1202. $this->options['union']['_all'] = true;
  1203. }
  1204. if(is_object($union)) {
  1205. $union = get_object_vars($union);
  1206. }
  1207. // 转换union表达式
  1208. if(is_string($union) ) {
  1209. $prefix = $this->tablePrefix;
  1210. //将__TABLE_NAME__字符串替换成带前缀的表名
  1211. $options = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $union);
  1212. }elseif(is_array($union)){
  1213. if(isset($union[0])) {
  1214. $this->options['union'] = array_merge($this->options['union'],$union);
  1215. return $this;
  1216. }else{
  1217. $options = $union;
  1218. }
  1219. }else{
  1220. E(L('_DATA_TYPE_INVALID_'));
  1221. }
  1222. $this->options['union'][] = $options;
  1223. return $this;
  1224. }
  1225. /**
  1226. * 查询缓存
  1227. * @access public
  1228. * @param mixed $key
  1229. * @param integer $expire
  1230. * @param string $type
  1231. * @return Model
  1232. */
  1233. public function cache($key=true,$expire=null,$type=''){
  1234. // 增加快捷调用方式 cache(10) 等同于 cache(true, 10)
  1235. if(is_numeric($key) && is_null($expire)){
  1236. $expire = $key;
  1237. $key = true;
  1238. }
  1239. if(false !== $key)
  1240. $this->options['cache'] = array('key'=>$key,'expire'=>$expire,'type'=>$type);
  1241. return $this;
  1242. }
  1243. /**
  1244. * 指定查询字段 支持字段排除
  1245. * @access public
  1246. * @param mixed $field
  1247. * @param boolean $except 是否排除
  1248. * @return Model
  1249. */
  1250. public function field($field,$except=false){
  1251. if(true === $field) {// 获取全部字段
  1252. $fields = $this->getDbFields();
  1253. $field = $fields?:'*';
  1254. }elseif($except) {// 字段排除
  1255. if(is_string($field)) {
  1256. $field = explode(',',$field);
  1257. }
  1258. $fields = $this->getDbFields();
  1259. $field = $fields?array_diff($fields,$field):$field;
  1260. }
  1261. $this->options['field'] = $field;
  1262. return $this;
  1263. }
  1264. /**
  1265. * 调用命名范围
  1266. * @access public
  1267. * @param mixed $scope 命名范围名称 支持多个 和直接定义
  1268. * @param array $args 参数
  1269. * @return Model
  1270. */
  1271. public function scope($scope='',$args=NULL){
  1272. if('' === $scope) {
  1273. if(isset($this->_scope['default'])) {
  1274. // 默认的命名范围
  1275. $options = $this->_scope['default'];
  1276. }else{
  1277. return $this;
  1278. }
  1279. }elseif(is_string($scope)){ // 支持多个命名范围调用 用逗号分割
  1280. $scopes = explode(',',$scope);
  1281. $options = array();
  1282. foreach ($scopes as $name){
  1283. if(!isset($this->_scope[$name])) continue;
  1284. $options = array_merge($options,$this->_scope[$name]);
  1285. }
  1286. if(!empty($args) && is_array($args)) {
  1287. $options = array_merge($options,$args);
  1288. }
  1289. }elseif(is_array($scope)){ // 直接传入命名范围定义
  1290. $options = $scope;
  1291. }
  1292. if(is_array($options) && !empty($options)){
  1293. $this->options = array_merge($this->options,array_change_key_case($options));
  1294. }
  1295. return $this;
  1296. }
  1297. /**
  1298. * 指定查询条件 支持安全过滤
  1299. * @access public
  1300. * @param mixed $where 条件表达式
  1301. * @param mixed $parse 预处理参数
  1302. * @return Model
  1303. */
  1304. public function where($where,$parse=null){
  1305. if(!is_null($parse) && is_string($where)) {
  1306. if(!is_array($parse)) {
  1307. $parse = func_get_args();
  1308. array_shift($parse);
  1309. }
  1310. $parse = array_map(array($this->db,'escapeString'),$parse);
  1311. $where = vsprintf($where,$parse);
  1312. }elseif(is_object($where)){
  1313. $where = get_object_vars($where);
  1314. }
  1315. if(is_string($where) && '' != $where){
  1316. $map = array();
  1317. $map['_string'] = $where;
  1318. $where = $map;
  1319. }
  1320. if(isset($this->options['where'])){
  1321. $this->options['where'] = array_merge($this->options['where'],$where);
  1322. }else{
  1323. $this->options['where'] = $where;
  1324. }
  1325. return $this;
  1326. }
  1327. /**
  1328. * 指定查询数量
  1329. * @access public
  1330. * @param mixed $offset 起始位置
  1331. * @param mixed $length 查询数量
  1332. * @return Model
  1333. */
  1334. public function limit($offset,$length=null){
  1335. if(is_null($length) && strpos($offset,',')){
  1336. list($offset,$length) = explode(',',$offset);
  1337. }
  1338. $this->options['limit'] = intval($offset).( $length? ','.intval($length) : '' );
  1339. return $this;
  1340. }
  1341. /**
  1342. * 指定分页
  1343. * @access public
  1344. * @param mixed $page 页数
  1345. * @param mixed $listRows 每页数量
  1346. * @return Model
  1347. */
  1348. public function page($page,$listRows=null){
  1349. if(is_null($listRows) && strpos($page,',')){
  1350. list($page,$listRows) = explode(',',$page);
  1351. }
  1352. $this->options['page'] = array(intval($page),intval($listRows));
  1353. return $this;
  1354. }
  1355. /**
  1356. * 查询注释
  1357. * @access public
  1358. * @param string $comment 注释
  1359. * @return Model
  1360. */
  1361. public function comment($comment){
  1362. $this->options['comment'] = $comment;
  1363. return $this;
  1364. }
  1365. /**
  1366. * 获取执行的SQL语句
  1367. * @access public
  1368. * @param boolean $fetch 是否返回sql
  1369. * @return Model
  1370. */
  1371. public function fetchSql($fetch){
  1372. $this->options['fetch_sql'] = $fetch;
  1373. return $this;
  1374. }
  1375. /**
  1376. * 参数绑定
  1377. * @access public
  1378. * @param string $key 参数名
  1379. * @param mixed $value 绑定的变量及绑定参数
  1380. * @return Model
  1381. */
  1382. public function bind($key,$value=false) {
  1383. if(is_array($key)){
  1384. $this->options['bind'] = $key;
  1385. }else{
  1386. $num = func_num_args();
  1387. if($num>2){
  1388. $params = func_get_args();
  1389. array_shift($params);
  1390. $this->options['bind'][$key] = $params;
  1391. }else{
  1392. $this->options['bind'][$key] = $value;
  1393. }
  1394. }
  1395. return $this;
  1396. }
  1397. /**
  1398. * 设置模型的属性值
  1399. * @access public
  1400. * @param string $name 名称
  1401. * @param mixed $value 值
  1402. * @return Model
  1403. */
  1404. public function setProperty($name,$value) {
  1405. if(property_exists($this,$name))
  1406. $this->$name = $value;
  1407. return $this;
  1408. }
  1409. }