Model.class.php 53 KB

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