Model.class.php 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2009 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. // $Id$
  12. define('HAS_ONE',1);
  13. define('BELONGS_TO',2);
  14. define('HAS_MANY',3);
  15. define('MANY_TO_MANY',4);
  16. /**
  17. +------------------------------------------------------------------------------
  18. * ThinkPHP Model模型类
  19. * 实现了ORM和ActiveRecords模式
  20. +------------------------------------------------------------------------------
  21. * @category Think
  22. * @package Think
  23. * @subpackage Core
  24. * @author liu21st <liu21st@gmail.com>
  25. * @version $Id$
  26. +------------------------------------------------------------------------------
  27. */
  28. class Model extends Think
  29. {
  30. // 操作状态
  31. const MODEL_INSERT = 1; // 插入模型数据
  32. const MODEL_UPDATE = 2; // 更新模型数据
  33. const MODEL_BOTH = 3; // 包含上面两种方式
  34. const MUST_VALIDATE = 1;// 必须验证
  35. const EXISTS_VAILIDATE = 0;// 表单存在字段则验证
  36. const VALUE_VAILIDATE = 2;// 表单值不为空则验证
  37. // 当前使用的扩展模型
  38. private $_extModel = null;
  39. // 当前数据库操作对象
  40. protected $db = null;
  41. // 主键名称
  42. protected $pk = 'id';
  43. // 数据表前缀
  44. protected $tablePrefix = '';
  45. // 数据表后缀
  46. protected $tableSuffix = '';
  47. // 模型名称
  48. protected $name = '';
  49. // 数据库名称
  50. protected $dbName = '';
  51. // 数据表名(不包含表前缀)
  52. protected $tableName = '';
  53. // 实际数据表名(包含表前缀)
  54. protected $trueTableName ='';
  55. // 最近错误信息
  56. protected $error = '';
  57. // 字段信息
  58. protected $fields = array();
  59. // 数据信息
  60. protected $data = array();
  61. // 查询表达式参数
  62. protected $options = array();
  63. protected $_validate = array(); // 自动验证定义
  64. protected $_auto = array(); // 自动完成定义
  65. protected $_map = array(); // 字段映射定义
  66. // 是否自动检测数据表字段信息
  67. protected $autoCheckFields = true;
  68. /**
  69. +----------------------------------------------------------
  70. * 架构函数
  71. * 取得DB类的实例对象 字段检查
  72. +----------------------------------------------------------
  73. * @param string $name 模型名称
  74. +----------------------------------------------------------
  75. * @access public
  76. +----------------------------------------------------------
  77. */
  78. public function __construct($name='')
  79. {
  80. // 模型初始化
  81. $this->_initialize();
  82. // 获取模型名称
  83. if(!empty($name)) {
  84. $this->name = $name;
  85. }elseif(empty($this->name)){
  86. $this->name = $this->getModelName();
  87. }
  88. // 数据库初始化操作
  89. // 获取数据库操作对象
  90. // 当前模型有独立的数据库连接信息
  91. $this->db = Db::getInstance(empty($this->connection)?'':$this->connection);
  92. // 设置表前缀
  93. $this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX');
  94. $this->tableSuffix = $this->tableSuffix?$this->tableSuffix:C('DB_SUFFIX');
  95. // 字段检测
  96. if(!empty($this->name) && $this->autoCheckFields) $this->_checkTableInfo();
  97. }
  98. /**
  99. +----------------------------------------------------------
  100. * 自动检测数据表信息
  101. +----------------------------------------------------------
  102. * @access protected
  103. +----------------------------------------------------------
  104. * @return void
  105. +----------------------------------------------------------
  106. */
  107. protected function _checkTableInfo() {
  108. // 如果不是Model类 自动记录数据表信息
  109. // 只在第一次执行记录
  110. if(empty($this->fields)) {
  111. // 如果数据表字段没有定义则自动获取
  112. if(C('DB_FIELDS_CACHE')) {
  113. $this->fields = F('_fields/'.$this->name);
  114. if(!$this->fields) $this->flush();
  115. }else{
  116. // 每次都会读取数据表信息
  117. $this->flush();
  118. }
  119. }
  120. }
  121. /**
  122. +----------------------------------------------------------
  123. * 获取字段信息并缓存
  124. +----------------------------------------------------------
  125. * @access public
  126. +----------------------------------------------------------
  127. * @return void
  128. +----------------------------------------------------------
  129. */
  130. public function flush() {
  131. // 缓存不存在则查询数据表信息
  132. $fields = $this->db->getFields($this->getTableName());
  133. $this->fields = array_keys($fields);
  134. $this->fields['_autoinc'] = false;
  135. foreach ($fields as $key=>$val){
  136. // 记录字段类型
  137. $type[$key] = $val['type'];
  138. if($val['primary']) {
  139. $this->fields['_pk'] = $key;
  140. if($val['autoinc']) $this->fields['_autoinc'] = true;
  141. }
  142. }
  143. // 记录字段类型信息
  144. if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type;
  145. // 2008-3-7 增加缓存开关控制
  146. if(C('DB_FIELDS_CACHE'))
  147. // 永久缓存数据表信息
  148. F('_fields/'.$this->name,$this->fields);
  149. }
  150. /**
  151. +----------------------------------------------------------
  152. * 动态切换扩展模型
  153. +----------------------------------------------------------
  154. * @access public
  155. +----------------------------------------------------------
  156. * @param string $type 模型类型名称
  157. * @param mixed $vars 要传入扩展模型的属性变量
  158. +----------------------------------------------------------
  159. * @return Model
  160. +----------------------------------------------------------
  161. */
  162. public function switchModel($type,$vars=array()) {
  163. $class = ucwords(strtolower($type)).'Model';
  164. if(!class_exists($class))
  165. throw_exception($class.L('_MODEL_NOT_EXIST_'));
  166. // 实例化扩展模型
  167. $this->_extModel = new $class($this->name);
  168. if(!empty($vars)) {
  169. // 传入当前模型的属性到扩展模型
  170. foreach ($vars as $var)
  171. $this->_extModel->setProperty($var,$this->$var);
  172. }
  173. return $this->_extModel;
  174. }
  175. /**
  176. +----------------------------------------------------------
  177. * 设置数据对象的值
  178. +----------------------------------------------------------
  179. * @access public
  180. +----------------------------------------------------------
  181. * @param string $name 名称
  182. * @param mixed $value 值
  183. +----------------------------------------------------------
  184. * @return void
  185. +----------------------------------------------------------
  186. */
  187. public function __set($name,$value) {
  188. // 设置数据对象属性
  189. $this->data[$name] = $value;
  190. }
  191. /**
  192. +----------------------------------------------------------
  193. * 获取数据对象的值
  194. +----------------------------------------------------------
  195. * @access public
  196. +----------------------------------------------------------
  197. * @param string $name 名称
  198. +----------------------------------------------------------
  199. * @return mixed
  200. +----------------------------------------------------------
  201. */
  202. public function __get($name) {
  203. return isset($this->data[$name])?$this->data[$name]:null;
  204. }
  205. /**
  206. +----------------------------------------------------------
  207. * 检测数据对象的值
  208. +----------------------------------------------------------
  209. * @access public
  210. +----------------------------------------------------------
  211. * @param string $name 名称
  212. +----------------------------------------------------------
  213. * @return boolean
  214. +----------------------------------------------------------
  215. */
  216. public function __isset($name) {
  217. return isset($this->data[$name]);
  218. }
  219. /**
  220. +----------------------------------------------------------
  221. * 销毁数据对象的值
  222. +----------------------------------------------------------
  223. * @access public
  224. +----------------------------------------------------------
  225. * @param string $name 名称
  226. +----------------------------------------------------------
  227. * @return void
  228. +----------------------------------------------------------
  229. */
  230. public function __unset($name) {
  231. unset($this->data[$name]);
  232. }
  233. /**
  234. +----------------------------------------------------------
  235. * 利用__call方法实现一些特殊的Model方法
  236. +----------------------------------------------------------
  237. * @access public
  238. +----------------------------------------------------------
  239. * @param string $method 方法名称
  240. * @param array $args 调用参数
  241. +----------------------------------------------------------
  242. * @return mixed
  243. +----------------------------------------------------------
  244. */
  245. public function __call($method,$args) {
  246. if(in_array(strtolower($method),array('field','table','where','order','limit','page','having','group','lock','distinct'),true)) {
  247. // 连贯操作的实现
  248. $this->options[strtolower($method)] = $args[0];
  249. return $this;
  250. }elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
  251. // 统计查询的实现
  252. $field = isset($args[0])?$args[0]:'*';
  253. return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method);
  254. }elseif(strtolower(substr($method,0,5))=='getby') {
  255. // 根据某个字段获取记录
  256. $field = parse_name(substr($method,5));
  257. $options['where'] = $field.'=\''.$args[0].'\'';
  258. return $this->find($options);
  259. }else{
  260. throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
  261. return;
  262. }
  263. }
  264. // 回调方法 初始化模型
  265. protected function _initialize() {}
  266. /**
  267. +----------------------------------------------------------
  268. * 对保存到数据库的数据进行处理
  269. +----------------------------------------------------------
  270. * @access protected
  271. +----------------------------------------------------------
  272. * @param mixed $data 要操作的数据
  273. +----------------------------------------------------------
  274. * @return boolean
  275. +----------------------------------------------------------
  276. */
  277. protected function _facade($data) {
  278. // 检查非数据字段
  279. if(!empty($this->fields)) {
  280. foreach ($data as $key=>$val){
  281. if(!in_array($key,$this->fields,true)){
  282. unset($data[$key]);
  283. }elseif(C('DB_FIELDTYPE_CHECK') && is_scalar($val)) {
  284. // 字段类型检查
  285. $fieldType = strtolower($this->fields['_type'][$key]);
  286. if(false !== strpos($fieldType,'int')) {
  287. $data[$key] = intval($val);
  288. }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){
  289. $data[$key] = floatval($val);
  290. }
  291. }
  292. }
  293. }
  294. $this->_before_write($data);
  295. return $data;
  296. }
  297. // 写入数据前的回调方法 包括新增和更新
  298. protected function _before_write(&$data) {}
  299. /**
  300. +----------------------------------------------------------
  301. * 新增数据
  302. +----------------------------------------------------------
  303. * @access public
  304. +----------------------------------------------------------
  305. * @param mixed $data 数据
  306. * @param array $options 表达式
  307. +----------------------------------------------------------
  308. * @return mixed
  309. +----------------------------------------------------------
  310. */
  311. public function add($data='',$options=array()) {
  312. if(empty($data)) {
  313. // 没有传递数据,获取当前数据对象的值
  314. if(!empty($this->data)) {
  315. $data = $this->data;
  316. }else{
  317. $this->error = L('_DATA_TYPE_INVALID_');
  318. return false;
  319. }
  320. }
  321. // 分析表达式
  322. $options = $this->_parseOptions($options);
  323. // 数据处理
  324. $data = $this->_facade($data);
  325. if(false === $this->_before_insert($data,$options)) {
  326. return false;
  327. }
  328. // 写入数据到数据库
  329. $result = $this->db->insert($data,$options);
  330. if(false !== $result ) {
  331. $insertId = $this->getLastInsID();
  332. if($insertId) {
  333. // 自增主键返回插入ID
  334. $data[$this->getPk()] = $insertId;
  335. $this->_after_insert($data,$options);
  336. return $insertId;
  337. }
  338. }
  339. return $result;
  340. }
  341. // 插入数据前的回调方法
  342. protected function _before_insert(&$data,$options) {}
  343. // 插入成功后的回调方法
  344. protected function _after_insert($data,$options) {}
  345. /**
  346. +----------------------------------------------------------
  347. * 通过Select方式添加记录
  348. +----------------------------------------------------------
  349. * @access public
  350. +----------------------------------------------------------
  351. * @param string $fields 要插入的数据表字段名
  352. * @param string $table 要插入的数据表名
  353. * @param array $options 表达式
  354. +----------------------------------------------------------
  355. * @return boolean
  356. +----------------------------------------------------------
  357. */
  358. public function selectAdd($fields='',$table='',$options=array()) {
  359. // 分析表达式
  360. $options = $this->_parseOptions($options);
  361. // 写入数据到数据库
  362. if(false === $result = $this->db->selectInsert($fields?$fields:$options['field'],$table?$table:$this->getTableName(),$options)){
  363. // 数据库插入操作失败
  364. $this->error = L('_OPERATION_WRONG_');
  365. return false;
  366. }else {
  367. // 插入成功
  368. return $result;
  369. }
  370. }
  371. /**
  372. +----------------------------------------------------------
  373. * 保存数据
  374. +----------------------------------------------------------
  375. * @access public
  376. +----------------------------------------------------------
  377. * @param mixed $data 数据
  378. * @param array $options 表达式
  379. +----------------------------------------------------------
  380. * @return boolean
  381. +----------------------------------------------------------
  382. */
  383. public function save($data='',$options=array()) {
  384. if(empty($data)) {
  385. // 没有传递数据,获取当前数据对象的值
  386. if(!empty($this->data)) {
  387. $data = $this->data;
  388. }else{
  389. $this->error = L('_DATA_TYPE_INVALID_');
  390. return false;
  391. }
  392. }
  393. // 数据处理
  394. $data = $this->_facade($data);
  395. // 分析表达式
  396. $options = $this->_parseOptions($options);
  397. if(false === $this->_before_update($data,$options)) {
  398. return false;
  399. }
  400. if(!isset($options['where']) ) {
  401. // 如果存在主键数据 则自动作为更新条件
  402. if(isset($data[$this->getPk()])) {
  403. $pk = $this->getPk();
  404. $options['where'] = $pk.'=\''.$data[$pk].'\'';
  405. $pkValue = $data[$pk];
  406. unset($data[$pk]);
  407. }else{
  408. // 如果没有任何更新条件则不执行
  409. $this->error = L('_OPERATION_WRONG_');
  410. return false;
  411. }
  412. }
  413. $result = $this->db->update($data,$options);
  414. if(false !== $result) {
  415. if(isset($pkValue)) $data[$pk] = $pkValue;
  416. $this->_after_update($data,$options);
  417. }
  418. return $result;
  419. }
  420. // 更新数据前的回调方法
  421. protected function _before_update(&$data,$options) {}
  422. // 更新成功后的回调方法
  423. protected function _after_update($data,$options) {}
  424. /**
  425. +----------------------------------------------------------
  426. * 删除数据
  427. +----------------------------------------------------------
  428. * @access public
  429. +----------------------------------------------------------
  430. * @param mixed $options 表达式
  431. +----------------------------------------------------------
  432. * @return mixed
  433. +----------------------------------------------------------
  434. */
  435. public function delete($options=array()) {
  436. if(empty($options) && empty($this->options)) {
  437. // 如果删除条件为空 则删除当前数据对象所对应的记录
  438. if(!empty($this->data) && isset($this->data[$this->getPk()]))
  439. return $this->delete($this->data[$this->getPk()]);
  440. else
  441. return false;
  442. }
  443. if(is_numeric($options) || is_string($options)) {
  444. // 根据主键删除记录
  445. $pk = $this->getPk();
  446. if(strpos($options,',')) {
  447. $where = $pk.' IN ('.$options.')';
  448. }else{
  449. $where = $pk.'=\''.$options.'\'';
  450. $pkValue = $options;
  451. }
  452. $options = array();
  453. $options['where'] = $where;
  454. }
  455. // 分析表达式
  456. $options = $this->_parseOptions($options);
  457. $result= $this->db->delete($options);
  458. if(false !== $result) {
  459. $data = array();
  460. if(isset($pkValue)) $data[$pk] = $pkValue;
  461. $this->_after_delete($data,$options);
  462. }
  463. // 返回删除记录个数
  464. return $result;
  465. }
  466. // 删除成功后的回调方法
  467. protected function _after_delete($data,$options) {}
  468. /**
  469. +----------------------------------------------------------
  470. * 查询数据集
  471. +----------------------------------------------------------
  472. * @access public
  473. +----------------------------------------------------------
  474. * @param array $options 表达式参数
  475. +----------------------------------------------------------
  476. * @return mixed
  477. +----------------------------------------------------------
  478. */
  479. public function select($options=array()) {
  480. if(is_string($options) || is_numeric($options)) {
  481. // 根据主键查询
  482. $where = $this->getPk().' IN ('.$options.')';
  483. $options = array();
  484. $options['where'] = $where;
  485. }
  486. // 分析表达式
  487. $options = $this->_parseOptions($options);
  488. $resultSet = $this->db->select($options);
  489. if(false === $resultSet) {
  490. return false;
  491. }
  492. if(empty($resultSet)) { // 查询结果为空
  493. return null;
  494. }
  495. $this->_after_select($resultSet,$options);
  496. return $resultSet;
  497. }
  498. // 查询成功后的回调方法
  499. protected function _after_select(&$resultSet,$options) {}
  500. public function findAll($options=array()) {
  501. return $this->select($options);
  502. }
  503. /**
  504. +----------------------------------------------------------
  505. * 分析表达式
  506. +----------------------------------------------------------
  507. * @access private
  508. +----------------------------------------------------------
  509. * @param array $options 表达式参数
  510. +----------------------------------------------------------
  511. * @return array
  512. +----------------------------------------------------------
  513. */
  514. private function _parseOptions($options) {
  515. if(is_array($options))
  516. $options = array_merge($this->options,$options);
  517. // 查询过后清空sql表达式组装 避免影响下次查询
  518. $this->options = array();
  519. if(!isset($options['table']))
  520. // 自动获取表名
  521. $options['table'] =$this->getTableName();
  522. // 字段类型验证
  523. if(C('DB_FIELDTYPE_CHECK')) {
  524. if(isset($options['where']) && is_array($options['where'])) {
  525. // 对数组查询条件进行字段类型检查
  526. foreach ($options['where'] as $key=>$val){
  527. if(in_array($key,$this->fields,true) && is_scalar($val)){
  528. $fieldType = strtolower($this->fields['_type'][$key]);
  529. if(false !== strpos($fieldType,'int')) {
  530. $options['where'][$key] = intval($val);
  531. }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){
  532. $options['where'][$key] = floatval($val);
  533. }
  534. }
  535. }
  536. }
  537. }
  538. // 表达式过滤
  539. $this->_options_filter($options);
  540. return $options;
  541. }
  542. // 表达式过滤回调方法
  543. protected function _options_filter(&$options) {}
  544. /**
  545. +----------------------------------------------------------
  546. * 查询数据
  547. +----------------------------------------------------------
  548. * @access public
  549. +----------------------------------------------------------
  550. * @param mixed $options 表达式参数
  551. +----------------------------------------------------------
  552. * @return mixed
  553. +----------------------------------------------------------
  554. */
  555. public function find($options=array()) {
  556. if(is_numeric($options) || is_string($options)) {
  557. $where = $this->getPk().'=\''.$options.'\'';
  558. $options = array();
  559. $options['where'] = $where;
  560. }
  561. // 总是查找一条记录
  562. $options['limit'] = 1;
  563. // 分析表达式
  564. $options = $this->_parseOptions($options);
  565. $resultSet = $this->db->select($options);
  566. if(false === $resultSet) {
  567. return false;
  568. }
  569. if(empty($resultSet)) {// 查询结果为空
  570. return null;
  571. }
  572. $this->data = $resultSet[0];
  573. $this->_after_find($this->data,$options);
  574. return $this->data;
  575. }
  576. // 查询成功的回调方法
  577. protected function _after_find(&$result,$options) {}
  578. /**
  579. +----------------------------------------------------------
  580. * 设置记录的某个字段值
  581. * 支持使用数据库字段和方法
  582. +----------------------------------------------------------
  583. * @access public
  584. +----------------------------------------------------------
  585. * @param string|array $field 字段名
  586. * @param string|array $value 字段值
  587. * @param mixed $condition 条件
  588. +----------------------------------------------------------
  589. * @return boolean
  590. +----------------------------------------------------------
  591. */
  592. public function setField($field,$value,$condition='') {
  593. if(empty($condition) && isset($this->options['where']))
  594. $condition = $this->options['where'];
  595. $options['where'] = $condition;
  596. if(is_array($field)) {
  597. foreach ($field as $key=>$val)
  598. $data[$val] = $value[$key];
  599. }else{
  600. $data[$field] = $value;
  601. }
  602. return $this->save($data,$options);
  603. }
  604. /**
  605. +----------------------------------------------------------
  606. * 字段值增长
  607. +----------------------------------------------------------
  608. * @access public
  609. +----------------------------------------------------------
  610. * @param string $field 字段名
  611. * @param mixed $condition 条件
  612. * @param integer $step 增长值
  613. +----------------------------------------------------------
  614. * @return boolean
  615. +----------------------------------------------------------
  616. */
  617. public function setInc($field,$condition='',$step=1) {
  618. return $this->setField($field,array('exp',$field.'+'.$step),$condition);
  619. }
  620. /**
  621. +----------------------------------------------------------
  622. * 字段值减少
  623. +----------------------------------------------------------
  624. * @access public
  625. +----------------------------------------------------------
  626. * @param string $field 字段名
  627. * @param mixed $condition 条件
  628. * @param integer $step 减少值
  629. +----------------------------------------------------------
  630. * @return boolean
  631. +----------------------------------------------------------
  632. */
  633. public function setDec($field,$condition='',$step=1) {
  634. return $this->setField($field,array('exp',$field.'-'.$step),$condition);
  635. }
  636. /**
  637. +----------------------------------------------------------
  638. * 获取一条记录的某个字段值
  639. +----------------------------------------------------------
  640. * @access public
  641. +----------------------------------------------------------
  642. * @param string $field 字段名
  643. * @param mixed $condition 查询条件
  644. * @param string $spea 字段数据间隔符号
  645. +----------------------------------------------------------
  646. * @return mixed
  647. +----------------------------------------------------------
  648. */
  649. public function getField($field,$condition='',$sepa=' ') {
  650. if(empty($condition) && isset($this->options['where']))
  651. $condition = $this->options['where'];
  652. $options['where'] = $condition;
  653. $options['field'] = $field;
  654. $options = $this->_parseOptions($options);
  655. if(strpos($field,',')) { // 多字段
  656. $resultSet = $this->db->select($options);
  657. if(!empty($resultSet)) {
  658. $field = explode(',',$field);
  659. $key = array_shift($field);
  660. $cols = array();
  661. foreach ($resultSet as $result){
  662. $name = $result[$key];
  663. $cols[$name] = '';
  664. foreach ($field as $val)
  665. $cols[$name] .= $result[$val].$sepa;
  666. $cols[$name] = substr($cols[$name],0,-strlen($sepa));
  667. }
  668. return $cols;
  669. }
  670. }else{ // 查找一条记录
  671. $options['limit'] = 1;
  672. $result = $this->db->select($options);
  673. if(!empty($result)) {
  674. return reset($result[0]);
  675. }
  676. }
  677. return null;
  678. }
  679. /**
  680. +----------------------------------------------------------
  681. * 创建数据对象 但不保存到数据库
  682. +----------------------------------------------------------
  683. * @access public
  684. +----------------------------------------------------------
  685. * @param mixed $data 创建数据
  686. * @param string $type 状态
  687. +----------------------------------------------------------
  688. * @return mixed
  689. +----------------------------------------------------------
  690. */
  691. public function create($data='',$type='') {
  692. // 如果没有传值默认取POST数据
  693. if(empty($data)) {
  694. filter_request($_POST);
  695. $data = $_POST;
  696. }elseif(is_object($data)){
  697. $data = get_object_vars($data);
  698. }elseif(!is_array($data)){
  699. $this->error = L('_DATA_TYPE_INVALID_');
  700. return false;
  701. }
  702. // 状态
  703. $type = $type?$type:(!empty($data[$this->getPk()])?self::MODEL_UPDATE:self::MODEL_INSERT);
  704. // 表单令牌验证
  705. if(C('TOKEN_ON') && !$this->autoCheckToken($data)) {
  706. $this->error = L('_TOKEN_ERROR_');
  707. return false;
  708. }
  709. // 数据自动验证
  710. if(!$this->autoValidation($data,$type)) return false;
  711. // 检查字段映射
  712. if(!empty($this->_map)) {
  713. foreach ($this->_map as $key=>$val){
  714. if(isset($data[$key])) {
  715. $data[$val] = $data[$key];
  716. unset($data[$key]);
  717. }
  718. }
  719. }
  720. // 验证完成生成数据对象
  721. $vo = array();
  722. foreach ($this->fields as $key=>$name){
  723. if(substr($key,0,1)=='_') continue;
  724. $val = isset($data[$name])?$data[$name]:null;
  725. //保证赋值有效
  726. if(!is_null($val)){
  727. $vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val;
  728. }
  729. }
  730. // 创建完成对数据进行自动处理
  731. $this->autoOperation($vo,$type);
  732. // 赋值当前数据对象
  733. $this->data = $vo;
  734. // 返回创建的数据以供其他调用
  735. return $vo;
  736. }
  737. // 自动表单令牌验证
  738. public function autoCheckToken($data) {
  739. $name = C('TOKEN_NAME');
  740. if(isset($_SESSION[$name])) {
  741. // 当前需要令牌验证
  742. if(empty($data[$name]) || $_SESSION[$name] != $data[$name]) {
  743. // 非法提交
  744. return false;
  745. }
  746. // 验证完成销毁session
  747. unset($_SESSION[$name]);
  748. }
  749. return true;
  750. }
  751. /**
  752. +----------------------------------------------------------
  753. * 使用正则验证数据
  754. +----------------------------------------------------------
  755. * @access public
  756. +----------------------------------------------------------
  757. * @param string $value 要验证的数据
  758. * @param string $rule 验证规则
  759. +----------------------------------------------------------
  760. * @return boolean
  761. +----------------------------------------------------------
  762. */
  763. public function regex($value,$rule) {
  764. $validate = array(
  765. 'require'=> '/.+/',
  766. 'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
  767. 'url' => '/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/',
  768. 'currency' => '/^\d+(\.\d+)?$/',
  769. 'number' => '/\d+$/',
  770. 'zip' => '/^[1-9]\d{5}$/',
  771. 'integer' => '/^[-\+]?\d+$/',
  772. 'double' => '/^[-\+]?\d+(\.\d+)?$/',
  773. 'english' => '/^[A-Za-z]+$/',
  774. );
  775. // 检查是否有内置的正则表达式
  776. if(isset($validate[strtolower($rule)]))
  777. $rule = $validate[strtolower($rule)];
  778. return preg_match($rule,$value)===1;
  779. }
  780. /**
  781. +----------------------------------------------------------
  782. * 自动表单处理
  783. +----------------------------------------------------------
  784. * @access public
  785. +----------------------------------------------------------
  786. * @param array $data 创建数据
  787. * @param string $type 创建类型
  788. +----------------------------------------------------------
  789. * @return mixed
  790. +----------------------------------------------------------
  791. */
  792. private function autoOperation(&$data,$type) {
  793. // 自动填充
  794. if(!empty($this->_auto)) {
  795. foreach ($this->_auto as $auto){
  796. // 填充因子定义格式
  797. // array('field','填充内容','填充条件','附加规则',[额外参数])
  798. if(empty($auto[2])) $auto[2] = self::MODEL_INSERT; // 默认为新增的时候自动填充
  799. if( $type == $auto[2] || $auto[2] == self::MODEL_BOTH) {
  800. switch($auto[3]) {
  801. case 'function': // 使用函数进行填充 字段的值作为参数
  802. case 'callback': // 使用回调方法
  803. $args = isset($auto[4])?$auto[4]:array();
  804. if(isset($data[$auto[0]])) {
  805. array_unshift($args,$data[$auto[0]]);
  806. }
  807. if('function'==$auto[3]) {
  808. $data[$auto[0]] = call_user_func_array($auto[1], $args);
  809. }else{
  810. $data[$auto[0]] = call_user_func_array(array(&$this,$auto[1]), $args);
  811. }
  812. break;
  813. case 'field': // 用其它字段的值进行填充
  814. $data[$auto[0]] = $data[$auto[1]];
  815. break;
  816. case 'string':
  817. default: // 默认作为字符串填充
  818. $data[$auto[0]] = $auto[1];
  819. }
  820. if(false === $data[$auto[0]] ) unset($data[$auto[0]]);
  821. }
  822. }
  823. }
  824. return $data;
  825. }
  826. /**
  827. +----------------------------------------------------------
  828. * 自动表单验证
  829. +----------------------------------------------------------
  830. * @access public
  831. +----------------------------------------------------------
  832. * @param array $data 创建数据
  833. * @param string $type 创建类型
  834. +----------------------------------------------------------
  835. * @return boolean
  836. +----------------------------------------------------------
  837. */
  838. private function autoValidation($data,$type) {
  839. // 属性验证
  840. if(!empty($this->_validate)) {
  841. // 如果设置了数据自动验证
  842. // 则进行数据验证
  843. // 重置验证错误信息
  844. foreach($this->_validate as $key=>$val) {
  845. // 验证因子定义格式
  846. // array(field,rule,message,condition,type,when,params)
  847. // 判断是否需要执行验证
  848. if(empty($val[5]) || $val[5]== self::MODEL_BOTH || $val[5]== $type ) {
  849. if(0==strpos($val[2],'{%') && strpos($val[2],'}'))
  850. // 支持提示信息的多语言 使用 {%语言定义} 方式
  851. $val[2] = L(substr($val[2],2,-1));
  852. $val[3] = isset($val[3])?$val[3]:self::EXISTS_VAILIDATE;
  853. $val[4] = isset($val[4])?$val[4]:'regex';
  854. // 判断验证条件
  855. switch($val[3]) {
  856. case self::MUST_VALIDATE: // 必须验证 不管表单是否有设置该字段
  857. if(false === $this->_validationField($data,$val)){
  858. $this->error = $val[2];
  859. return false;
  860. }
  861. break;
  862. case self::VALUE_VAILIDATE: // 值不为空的时候才验证
  863. if('' != trim($data[$val[0]])){
  864. if(false === $this->_validationField($data,$val)){
  865. $this->error = $val[2];
  866. return false;
  867. }
  868. }
  869. break;
  870. default: // 默认表单存在该字段就验证
  871. if(isset($data[$val[0]])){
  872. if(false === $this->_validationField($data,$val)){
  873. $this->error = $val[2];
  874. return false;
  875. }
  876. }
  877. }
  878. }
  879. }
  880. }
  881. return true;
  882. }
  883. /**
  884. +----------------------------------------------------------
  885. * 根据验证因子验证字段
  886. +----------------------------------------------------------
  887. * @access public
  888. +----------------------------------------------------------
  889. * @param array $data 创建数据
  890. * @param string $val 验证规则
  891. +----------------------------------------------------------
  892. * @return boolean
  893. +----------------------------------------------------------
  894. */
  895. private function _validationField($data,$val) {
  896. switch($val[4]) {
  897. case 'function':// 使用函数进行验证
  898. case 'callback':// 调用方法进行验证
  899. $args = isset($val[6])?$val[6]:array();
  900. array_unshift($args,$data[$val[0]]);
  901. if('function'==$val[4]) {
  902. return call_user_func_array($val[1], $args);
  903. }else{
  904. return call_user_func_array(array(&$this, $val[1]), $args);
  905. }
  906. case 'confirm': // 验证两个字段是否相同
  907. return $data[$val[0]] == $data[$val[1]];
  908. case 'in': // 验证是否在某个数组范围之内
  909. return in_array($data[$val[0]] ,$val[1]);
  910. case 'equal': // 验证是否等于某个值
  911. return $data[$val[0]] == $val[1];
  912. case 'unique': // 验证某个值是否唯一
  913. if(is_string($val[0]) && strpos($val[0],','))
  914. $val[0] = explode(',',$val[0]);
  915. $map = array();
  916. if(is_array($val[0])) {
  917. // 支持多个字段验证
  918. foreach ($val[0] as $field)
  919. $map[$field] = $data[$field];
  920. }else{
  921. $map[$val[0]] = $data[$val[0]];
  922. }
  923. if($this->where($map)->find())
  924. return false;
  925. break;
  926. case 'regex':
  927. default: // 默认使用正则验证 可以使用验证类中定义的验证名称
  928. // 检查附加规则
  929. return $this->regex($data[$val[0]],$val[1]);
  930. }
  931. return true;
  932. }
  933. /**
  934. +----------------------------------------------------------
  935. * SQL查询
  936. +----------------------------------------------------------
  937. * @access public
  938. +----------------------------------------------------------
  939. * @param mixed $sql SQL指令
  940. +----------------------------------------------------------
  941. * @return mixed
  942. +----------------------------------------------------------
  943. */
  944. public function query($sql)
  945. {
  946. if(!empty($sql)) {
  947. if(strpos($sql,'__TABLE__'))
  948. $sql = str_replace('__TABLE__',$this->getTableName(),$sql);
  949. return $this->db->query($sql);
  950. }else{
  951. return false;
  952. }
  953. }
  954. /**
  955. +----------------------------------------------------------
  956. * 执行SQL语句
  957. +----------------------------------------------------------
  958. * @access public
  959. +----------------------------------------------------------
  960. * @param string $sql SQL指令
  961. +----------------------------------------------------------
  962. * @return false | integer
  963. +----------------------------------------------------------
  964. */
  965. public function execute($sql)
  966. {
  967. if(!empty($sql)) {
  968. if(strpos($sql,'__TABLE__'))
  969. $sql = str_replace('__TABLE__',$this->getTableName(),$sql);
  970. return $this->db->execute($sql);
  971. }else {
  972. return false;
  973. }
  974. }
  975. /**
  976. +----------------------------------------------------------
  977. * 得到当前的数据对象名称
  978. +----------------------------------------------------------
  979. * @access public
  980. +----------------------------------------------------------
  981. * @return string
  982. +----------------------------------------------------------
  983. */
  984. public function getModelName()
  985. {
  986. if(empty($this->name))
  987. $this->name = substr(get_class($this),0,-5);
  988. return $this->name;
  989. }
  990. /**
  991. +----------------------------------------------------------
  992. * 得到完整的数据表名
  993. +----------------------------------------------------------
  994. * @access public
  995. +----------------------------------------------------------
  996. * @return string
  997. +----------------------------------------------------------
  998. */
  999. public function getTableName()
  1000. {
  1001. if(empty($this->trueTableName)) {
  1002. $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
  1003. if(!empty($this->tableName)) {
  1004. $tableName .= $this->tableName;
  1005. }else{
  1006. $tableName .= parse_name($this->name);
  1007. }
  1008. $tableName .= !empty($this->tableSuffix) ? $this->tableSuffix : '';
  1009. if(!empty($this->dbName))
  1010. $tableName = $this->dbName.'.'.$tableName;
  1011. $this->trueTableName = strtolower($tableName);
  1012. }
  1013. return $this->trueTableName;
  1014. }
  1015. /**
  1016. +----------------------------------------------------------
  1017. * 启动事务
  1018. +----------------------------------------------------------
  1019. * @access public
  1020. +----------------------------------------------------------
  1021. * @return void
  1022. +----------------------------------------------------------
  1023. */
  1024. public function startTrans()
  1025. {
  1026. $this->commit();
  1027. $this->db->startTrans();
  1028. return ;
  1029. }
  1030. /**
  1031. +----------------------------------------------------------
  1032. * 提交事务
  1033. +----------------------------------------------------------
  1034. * @access public
  1035. +----------------------------------------------------------
  1036. * @return boolean
  1037. +----------------------------------------------------------
  1038. */
  1039. public function commit()
  1040. {
  1041. return $this->db->commit();
  1042. }
  1043. /**
  1044. +----------------------------------------------------------
  1045. * 事务回滚
  1046. +----------------------------------------------------------
  1047. * @access public
  1048. +----------------------------------------------------------
  1049. * @return boolean
  1050. +----------------------------------------------------------
  1051. */
  1052. public function rollback()
  1053. {
  1054. return $this->db->rollback();
  1055. }
  1056. /**
  1057. +----------------------------------------------------------
  1058. * 返回模型的错误信息
  1059. +----------------------------------------------------------
  1060. * @access public
  1061. +----------------------------------------------------------
  1062. * @return string
  1063. +----------------------------------------------------------
  1064. */
  1065. public function getError(){
  1066. return $this->error;
  1067. }
  1068. /**
  1069. +----------------------------------------------------------
  1070. * 返回数据库的错误信息
  1071. +----------------------------------------------------------
  1072. * @access public
  1073. +----------------------------------------------------------
  1074. * @return string
  1075. +----------------------------------------------------------
  1076. */
  1077. public function getDbError() {
  1078. return $this->db->getError();
  1079. }
  1080. /**
  1081. +----------------------------------------------------------
  1082. * 返回最后插入的ID
  1083. +----------------------------------------------------------
  1084. * @access public
  1085. +----------------------------------------------------------
  1086. * @return string
  1087. +----------------------------------------------------------
  1088. */
  1089. public function getLastInsID() {
  1090. return $this->db->lastInsID;
  1091. }
  1092. /**
  1093. +----------------------------------------------------------
  1094. * 返回最后执行的sql语句
  1095. +----------------------------------------------------------
  1096. * @access public
  1097. +----------------------------------------------------------
  1098. * @return string
  1099. +----------------------------------------------------------
  1100. */
  1101. public function getLastSql() {
  1102. return $this->db->getLastSql();
  1103. }
  1104. /**
  1105. +----------------------------------------------------------
  1106. * 获取主键名称
  1107. +----------------------------------------------------------
  1108. * @access public
  1109. +----------------------------------------------------------
  1110. * @return string
  1111. +----------------------------------------------------------
  1112. */
  1113. public function getPk() {
  1114. return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk;
  1115. }
  1116. /**
  1117. +----------------------------------------------------------
  1118. * 获取数据表字段信息
  1119. +----------------------------------------------------------
  1120. * @access public
  1121. +----------------------------------------------------------
  1122. * @return array
  1123. +----------------------------------------------------------
  1124. */
  1125. public function getDbFields(){
  1126. return $this->fields;
  1127. }
  1128. /**
  1129. +----------------------------------------------------------
  1130. * 设置数据对象值
  1131. +----------------------------------------------------------
  1132. * @access public
  1133. +----------------------------------------------------------
  1134. * @param mixed $data 数据
  1135. +----------------------------------------------------------
  1136. * @return Model
  1137. +----------------------------------------------------------
  1138. */
  1139. public function data($data){
  1140. if(is_object($data)){
  1141. $data = get_object_vars($data);
  1142. }elseif(!is_array($data)){
  1143. throw_exception(L('_DATA_TYPE_INVALID_'));
  1144. }
  1145. $this->data = $data;
  1146. return $this;
  1147. }
  1148. /**
  1149. +----------------------------------------------------------
  1150. * 查询SQL组装 join
  1151. +----------------------------------------------------------
  1152. * @access public
  1153. +----------------------------------------------------------
  1154. * @param mixed $join
  1155. +----------------------------------------------------------
  1156. * @return Model
  1157. +----------------------------------------------------------
  1158. */
  1159. public function join($join) {
  1160. if(is_array($join))
  1161. $this->options['join'] = $join;
  1162. else
  1163. $this->options['join'][] = $join;
  1164. return $this;
  1165. }
  1166. /**
  1167. +----------------------------------------------------------
  1168. * 设置模型的属性值
  1169. +----------------------------------------------------------
  1170. * @access public
  1171. +----------------------------------------------------------
  1172. * @param string $name 名称
  1173. * @param mixed $value 值
  1174. +----------------------------------------------------------
  1175. * @return Model
  1176. +----------------------------------------------------------
  1177. */
  1178. public function setProperty($name,$value) {
  1179. if(property_exists($this,$name))
  1180. $this->$name = $value;
  1181. return $this;
  1182. }
  1183. };
  1184. ?>