Model.class.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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. $data = $_POST;
  695. }elseif(is_object($data)){
  696. $data = get_object_vars($data);
  697. }elseif(!is_array($data)){
  698. $this->error = L('_DATA_TYPE_INVALID_');
  699. return false;
  700. }
  701. // 状态
  702. $type = $type?$type:(!empty($data[$this->getPk()])?self::MODEL_UPDATE:self::MODEL_INSERT);
  703. // 表单令牌验证
  704. if(C('TOKEN_ON') && !$this->autoCheckToken($data)) {
  705. $this->error = L('_TOKEN_ERROR_');
  706. return false;
  707. }
  708. // 数据自动验证
  709. if(!$this->autoValidation($data,$type)) return false;
  710. // 检查字段映射
  711. if(!empty($this->_map)) {
  712. foreach ($this->_map as $key=>$val){
  713. if(isset($data[$key])) {
  714. $data[$val] = $data[$key];
  715. unset($data[$key]);
  716. }
  717. }
  718. }
  719. // 验证完成生成数据对象
  720. $vo = array();
  721. foreach ($this->fields as $key=>$name){
  722. if(substr($key,0,1)=='_') continue;
  723. $val = isset($data[$name])?$data[$name]:null;
  724. //保证赋值有效
  725. if(!is_null($val)){
  726. $vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val;
  727. }
  728. }
  729. // 创建完成对数据进行自动处理
  730. $this->autoOperation($vo,$type);
  731. // 赋值当前数据对象
  732. $this->data = $vo;
  733. // 返回创建的数据以供其他调用
  734. return $vo;
  735. }
  736. // 自动表单令牌验证
  737. public function autoCheckToken($data) {
  738. $name = C('TOKEN_NAME');
  739. if(isset($_SESSION[$name])) {
  740. // 当前需要令牌验证
  741. if(empty($data[$name]) || $_SESSION[$name] != $data[$name]) {
  742. // 非法提交
  743. return false;
  744. }
  745. // 验证完成销毁session
  746. unset($_SESSION[$name]);
  747. }
  748. return true;
  749. }
  750. /**
  751. +----------------------------------------------------------
  752. * 使用正则验证数据
  753. +----------------------------------------------------------
  754. * @access public
  755. +----------------------------------------------------------
  756. * @param string $value 要验证的数据
  757. * @param string $rule 验证规则
  758. +----------------------------------------------------------
  759. * @return boolean
  760. +----------------------------------------------------------
  761. */
  762. public function regex($value,$rule) {
  763. $validate = array(
  764. 'require'=> '/.+/',
  765. 'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
  766. 'url' => '/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/',
  767. 'currency' => '/^\d+(\.\d+)?$/',
  768. 'number' => '/\d+$/',
  769. 'zip' => '/^[1-9]\d{5}$/',
  770. 'integer' => '/^[-\+]?\d+$/',
  771. 'double' => '/^[-\+]?\d+(\.\d+)?$/',
  772. 'english' => '/^[A-Za-z]+$/',
  773. );
  774. // 检查是否有内置的正则表达式
  775. if(isset($validate[strtolower($rule)]))
  776. $rule = $validate[strtolower($rule)];
  777. return preg_match($rule,$value)===1;
  778. }
  779. /**
  780. +----------------------------------------------------------
  781. * 自动表单处理
  782. +----------------------------------------------------------
  783. * @access public
  784. +----------------------------------------------------------
  785. * @param array $data 创建数据
  786. * @param string $type 创建类型
  787. +----------------------------------------------------------
  788. * @return mixed
  789. +----------------------------------------------------------
  790. */
  791. private function autoOperation(&$data,$type) {
  792. // 自动填充
  793. if(!empty($this->_auto)) {
  794. foreach ($this->_auto as $auto){
  795. // 填充因子定义格式
  796. // array('field','填充内容','填充条件','附加规则',[额外参数])
  797. if(empty($auto[2])) $auto[2] = self::MODEL_INSERT; // 默认为新增的时候自动填充
  798. if( $type == $auto[2] || $auto[2] == self::MODEL_BOTH) {
  799. switch($auto[3]) {
  800. case 'function': // 使用函数进行填充 字段的值作为参数
  801. case 'callback': // 使用回调方法
  802. $args = isset($auto[4])?$auto[4]:array();
  803. if(isset($data[$auto[0]])) {
  804. array_unshift($args,$data[$auto[0]]);
  805. }
  806. if('function'==$auto[3]) {
  807. $data[$auto[0]] = call_user_func_array($auto[1], $args);
  808. }else{
  809. $data[$auto[0]] = call_user_func_array(array(&$this,$auto[1]), $args);
  810. }
  811. break;
  812. case 'field': // 用其它字段的值进行填充
  813. $data[$auto[0]] = $data[$auto[1]];
  814. break;
  815. case 'string':
  816. default: // 默认作为字符串填充
  817. $data[$auto[0]] = $auto[1];
  818. }
  819. if(false === $data[$auto[0]] ) unset($data[$auto[0]]);
  820. }
  821. }
  822. }
  823. return $data;
  824. }
  825. /**
  826. +----------------------------------------------------------
  827. * 自动表单验证
  828. +----------------------------------------------------------
  829. * @access public
  830. +----------------------------------------------------------
  831. * @param array $data 创建数据
  832. * @param string $type 创建类型
  833. +----------------------------------------------------------
  834. * @return boolean
  835. +----------------------------------------------------------
  836. */
  837. private function autoValidation($data,$type) {
  838. // 属性验证
  839. if(!empty($this->_validate)) {
  840. // 如果设置了数据自动验证
  841. // 则进行数据验证
  842. // 重置验证错误信息
  843. foreach($this->_validate as $key=>$val) {
  844. // 验证因子定义格式
  845. // array(field,rule,message,condition,type,when,params)
  846. // 判断是否需要执行验证
  847. if(empty($val[5]) || $val[5]== self::MODEL_BOTH || $val[5]== $type ) {
  848. if(0==strpos($val[2],'{%') && strpos($val[2],'}'))
  849. // 支持提示信息的多语言 使用 {%语言定义} 方式
  850. $val[2] = L(substr($val[2],2,-1));
  851. $val[3] = isset($val[3])?$val[3]:self::EXISTS_VAILIDATE;
  852. $val[4] = isset($val[4])?$val[4]:'regex';
  853. // 判断验证条件
  854. switch($val[3]) {
  855. case self::MUST_VALIDATE: // 必须验证 不管表单是否有设置该字段
  856. if(false === $this->_validationField($data,$val)){
  857. $this->error = $val[2];
  858. return false;
  859. }
  860. break;
  861. case self::VALUE_VAILIDATE: // 值不为空的时候才验证
  862. if('' != trim($data[$val[0]])){
  863. if(false === $this->_validationField($data,$val)){
  864. $this->error = $val[2];
  865. return false;
  866. }
  867. }
  868. break;
  869. default: // 默认表单存在该字段就验证
  870. if(isset($data[$val[0]])){
  871. if(false === $this->_validationField($data,$val)){
  872. $this->error = $val[2];
  873. return false;
  874. }
  875. }
  876. }
  877. }
  878. }
  879. }
  880. return true;
  881. }
  882. /**
  883. +----------------------------------------------------------
  884. * 根据验证因子验证字段
  885. +----------------------------------------------------------
  886. * @access public
  887. +----------------------------------------------------------
  888. * @param array $data 创建数据
  889. * @param string $val 验证规则
  890. +----------------------------------------------------------
  891. * @return boolean
  892. +----------------------------------------------------------
  893. */
  894. private function _validationField($data,$val) {
  895. switch($val[4]) {
  896. case 'function':// 使用函数进行验证
  897. case 'callback':// 调用方法进行验证
  898. $args = isset($val[6])?$val[6]:array();
  899. array_unshift($args,$data[$val[0]]);
  900. if('function'==$val[4]) {
  901. return call_user_func_array($val[1], $args);
  902. }else{
  903. return call_user_func_array(array(&$this, $val[1]), $args);
  904. }
  905. case 'confirm': // 验证两个字段是否相同
  906. return $data[$val[0]] == $data[$val[1]];
  907. case 'in': // 验证是否在某个数组范围之内
  908. return in_array($data[$val[0]] ,$val[1]);
  909. case 'equal': // 验证是否等于某个值
  910. return $data[$val[0]] == $val[1];
  911. case 'unique': // 验证某个值是否唯一
  912. if(is_string($val[0]) && strpos($val[0],','))
  913. $val[0] = explode(',',$val[0]);
  914. $map = array();
  915. if(is_array($val[0])) {
  916. // 支持多个字段验证
  917. foreach ($val[0] as $field)
  918. $map[$field] = $data[$field];
  919. }else{
  920. $map[$val[0]] = $data[$val[0]];
  921. }
  922. if($this->where($map)->find())
  923. return false;
  924. break;
  925. case 'regex':
  926. default: // 默认使用正则验证 可以使用验证类中定义的验证名称
  927. // 检查附加规则
  928. return $this->regex($data[$val[0]],$val[1]);
  929. }
  930. return true;
  931. }
  932. /**
  933. +----------------------------------------------------------
  934. * SQL查询
  935. +----------------------------------------------------------
  936. * @access public
  937. +----------------------------------------------------------
  938. * @param mixed $sql SQL指令
  939. +----------------------------------------------------------
  940. * @return mixed
  941. +----------------------------------------------------------
  942. */
  943. public function query($sql)
  944. {
  945. if(!empty($sql)) {
  946. if(strpos($sql,'__TABLE__'))
  947. $sql = str_replace('__TABLE__',$this->getTableName(),$sql);
  948. return $this->db->query($sql);
  949. }else{
  950. return false;
  951. }
  952. }
  953. /**
  954. +----------------------------------------------------------
  955. * 执行SQL语句
  956. +----------------------------------------------------------
  957. * @access public
  958. +----------------------------------------------------------
  959. * @param string $sql SQL指令
  960. +----------------------------------------------------------
  961. * @return false | integer
  962. +----------------------------------------------------------
  963. */
  964. public function execute($sql)
  965. {
  966. if(!empty($sql)) {
  967. if(strpos($sql,'__TABLE__'))
  968. $sql = str_replace('__TABLE__',$this->getTableName(),$sql);
  969. return $this->db->execute($sql);
  970. }else {
  971. return false;
  972. }
  973. }
  974. /**
  975. +----------------------------------------------------------
  976. * 得到当前的数据对象名称
  977. +----------------------------------------------------------
  978. * @access public
  979. +----------------------------------------------------------
  980. * @return string
  981. +----------------------------------------------------------
  982. */
  983. public function getModelName()
  984. {
  985. if(empty($this->name))
  986. $this->name = substr(get_class($this),0,-5);
  987. return $this->name;
  988. }
  989. /**
  990. +----------------------------------------------------------
  991. * 得到完整的数据表名
  992. +----------------------------------------------------------
  993. * @access public
  994. +----------------------------------------------------------
  995. * @return string
  996. +----------------------------------------------------------
  997. */
  998. public function getTableName()
  999. {
  1000. if(empty($this->trueTableName)) {
  1001. $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
  1002. if(!empty($this->tableName)) {
  1003. $tableName .= $this->tableName;
  1004. }else{
  1005. $tableName .= parse_name($this->name);
  1006. }
  1007. $tableName .= !empty($this->tableSuffix) ? $this->tableSuffix : '';
  1008. if(!empty($this->dbName))
  1009. $tableName = $this->dbName.'.'.$tableName;
  1010. $this->trueTableName = strtolower($tableName);
  1011. }
  1012. return $this->trueTableName;
  1013. }
  1014. /**
  1015. +----------------------------------------------------------
  1016. * 启动事务
  1017. +----------------------------------------------------------
  1018. * @access public
  1019. +----------------------------------------------------------
  1020. * @return void
  1021. +----------------------------------------------------------
  1022. */
  1023. public function startTrans()
  1024. {
  1025. $this->commit();
  1026. $this->db->startTrans();
  1027. return ;
  1028. }
  1029. /**
  1030. +----------------------------------------------------------
  1031. * 提交事务
  1032. +----------------------------------------------------------
  1033. * @access public
  1034. +----------------------------------------------------------
  1035. * @return boolean
  1036. +----------------------------------------------------------
  1037. */
  1038. public function commit()
  1039. {
  1040. return $this->db->commit();
  1041. }
  1042. /**
  1043. +----------------------------------------------------------
  1044. * 事务回滚
  1045. +----------------------------------------------------------
  1046. * @access public
  1047. +----------------------------------------------------------
  1048. * @return boolean
  1049. +----------------------------------------------------------
  1050. */
  1051. public function rollback()
  1052. {
  1053. return $this->db->rollback();
  1054. }
  1055. /**
  1056. +----------------------------------------------------------
  1057. * 返回模型的错误信息
  1058. +----------------------------------------------------------
  1059. * @access public
  1060. +----------------------------------------------------------
  1061. * @return string
  1062. +----------------------------------------------------------
  1063. */
  1064. public function getError(){
  1065. return $this->error;
  1066. }
  1067. /**
  1068. +----------------------------------------------------------
  1069. * 返回数据库的错误信息
  1070. +----------------------------------------------------------
  1071. * @access public
  1072. +----------------------------------------------------------
  1073. * @return string
  1074. +----------------------------------------------------------
  1075. */
  1076. public function getDbError() {
  1077. return $this->db->getError();
  1078. }
  1079. /**
  1080. +----------------------------------------------------------
  1081. * 返回最后插入的ID
  1082. +----------------------------------------------------------
  1083. * @access public
  1084. +----------------------------------------------------------
  1085. * @return string
  1086. +----------------------------------------------------------
  1087. */
  1088. public function getLastInsID() {
  1089. return $this->db->lastInsID;
  1090. }
  1091. /**
  1092. +----------------------------------------------------------
  1093. * 返回最后执行的sql语句
  1094. +----------------------------------------------------------
  1095. * @access public
  1096. +----------------------------------------------------------
  1097. * @return string
  1098. +----------------------------------------------------------
  1099. */
  1100. public function getLastSql() {
  1101. return $this->db->getLastSql();
  1102. }
  1103. /**
  1104. +----------------------------------------------------------
  1105. * 获取主键名称
  1106. +----------------------------------------------------------
  1107. * @access public
  1108. +----------------------------------------------------------
  1109. * @return string
  1110. +----------------------------------------------------------
  1111. */
  1112. public function getPk() {
  1113. return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk;
  1114. }
  1115. /**
  1116. +----------------------------------------------------------
  1117. * 获取数据表字段信息
  1118. +----------------------------------------------------------
  1119. * @access public
  1120. +----------------------------------------------------------
  1121. * @return array
  1122. +----------------------------------------------------------
  1123. */
  1124. public function getDbFields(){
  1125. return $this->fields;
  1126. }
  1127. /**
  1128. +----------------------------------------------------------
  1129. * 设置数据对象值
  1130. +----------------------------------------------------------
  1131. * @access public
  1132. +----------------------------------------------------------
  1133. * @param mixed $data 数据
  1134. +----------------------------------------------------------
  1135. * @return Model
  1136. +----------------------------------------------------------
  1137. */
  1138. public function data($data){
  1139. if(is_object($data)){
  1140. $data = get_object_vars($data);
  1141. }elseif(!is_array($data)){
  1142. throw_exception(L('_DATA_TYPE_INVALID_'));
  1143. }
  1144. $this->data = $data;
  1145. return $this;
  1146. }
  1147. /**
  1148. +----------------------------------------------------------
  1149. * 查询SQL组装 join
  1150. +----------------------------------------------------------
  1151. * @access public
  1152. +----------------------------------------------------------
  1153. * @param mixed $join
  1154. +----------------------------------------------------------
  1155. * @return Model
  1156. +----------------------------------------------------------
  1157. */
  1158. public function join($join) {
  1159. if(is_array($join))
  1160. $this->options['join'] = $join;
  1161. else
  1162. $this->options['join'][] = $join;
  1163. return $this;
  1164. }
  1165. /**
  1166. +----------------------------------------------------------
  1167. * 设置模型的属性值
  1168. +----------------------------------------------------------
  1169. * @access public
  1170. +----------------------------------------------------------
  1171. * @param string $name 名称
  1172. * @param mixed $value 值
  1173. +----------------------------------------------------------
  1174. * @return Model
  1175. +----------------------------------------------------------
  1176. */
  1177. public function setProperty($name,$value) {
  1178. if(property_exists($this,$name))
  1179. $this->$name = $value;
  1180. return $this;
  1181. }
  1182. };
  1183. ?>