Base.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. <?php
  2. namespace Qii\Driver;
  3. class Base
  4. {
  5. const VERSION = '1.2';
  6. public $_cache;
  7. public $language;
  8. protected $_query = array(
  9. "INSERT" => "INSERT INTO %s(%s) VALUES('%s')",
  10. "REPLACE" => "REPLACE %s (%s) VALUES('%s')",
  11. "SELECT" => "SELECT %s FROM %s",
  12. "UPDATE" => "UPDATE %s SET ",
  13. "DELETE" => "DELETE FROM %s %s",
  14. "WHERE" => " WHERE %s",
  15. "ORDER" => " ORDER BY %s %s",
  16. "GROUP" => " GROUP BY %s",
  17. "LIMIT" => " LIMIT %d, %d"
  18. );
  19. private $query;
  20. private $setArray = array();
  21. public $modelSQL = "";
  22. protected $fields;
  23. protected $where;
  24. protected $groupBy;
  25. protected $limit;
  26. protected $orderBy;
  27. public $load;
  28. /**
  29. * @var string $_response Response对象
  30. */
  31. protected $_response;
  32. //方法对应的别名
  33. protected $_modelAlias = array('selectRows' => 'selectAll', 'select' => 'selectRow', 'getOne' => 'selectOne', 'getRow' => 'selectRow', 'getAll' => 'selectAll', 'remove' => 'deleteRows');
  34. public function __construct()
  35. {
  36. $this->language = \Qii\Autoloader\Psr4::getInstance()->loadClass('Qii\Language\Loader');
  37. $this->load = \Qii\Autoloader\Psr4::getInstance()->loadClass('\Qii\Autoloader\Loader');
  38. $this->_response = new \Qii\Driver\Response();
  39. }
  40. /**
  41. * 获取数据库中所有的数据表
  42. * @return array
  43. */
  44. public function getAllDatabases()
  45. {
  46. $sql = "SHOW DATABASES";
  47. $rs = $this->setQuery($sql);
  48. $database = array();
  49. while($row = $rs->fetch())
  50. {
  51. $database[] = $row['Database'];
  52. }
  53. return $database;
  54. }
  55. /**
  56. * 数据库中是否包含指定库
  57. * @param string $database 数据库名
  58. * @return bool
  59. */
  60. public function hasDatabase($database)
  61. {
  62. if(!$database) return false;
  63. $sql = "SHOW DATABASES LIKE '". $database ."'";
  64. $rs = $this->setQuery($sql);
  65. while($row = $rs->fetch())
  66. {
  67. $val = array_values($row);
  68. if(in_array($database, $val))
  69. {
  70. return true;
  71. }
  72. }
  73. return false;
  74. }
  75. /**
  76. * 获取当前数据库中所有的表
  77. * @param null|string $database 数据库
  78. * @return array
  79. */
  80. public function getAllTables($database = null)
  81. {
  82. if($database)
  83. {
  84. $this->setQuery('USE '. $database);
  85. }
  86. $sql = "SHOW TABLES";
  87. $rs = $this->setQuery($sql);
  88. $tables = array();
  89. while($row = $rs->fetch())
  90. {
  91. if(is_array($row)) {
  92. foreach($row AS $val) {
  93. $tables[] = $val;
  94. }
  95. }
  96. }
  97. return $tables;
  98. }
  99. /**
  100. * 获取指定数据表的所有字段
  101. * @param string $table 表名
  102. * @param string $database 数据库名
  103. * @return array
  104. */
  105. public function getTableInfo($table, $database = null)
  106. {
  107. if(!$database) $database = $this->currentDB;
  108. $sql = "SELECT * from information_schema.COLUMNS where table_name = '".$table."' and table_schema = '".$database."'";
  109. $data = ['fields' => [],
  110. 'rules' => [
  111. 'pri' => [], 'required' => []
  112. ]
  113. ];
  114. $rs = $this->setQuery($sql);
  115. while($row = $rs->fetch())
  116. {
  117. $data['fields'][] = $row['COLUMN_NAME'];
  118. if($row['EXTRA'])
  119. {
  120. $data['rules']['extra'][$row['EXTRA']][] = $row['COLUMN_NAME'];
  121. }
  122. if($row['COLUMN_KEY'] == 'PRI')
  123. {
  124. $data['rules']['pri'][] = $row['COLUMN_NAME'];
  125. $data['rules']['required'][] = $row['COLUMN_NAME'];
  126. }
  127. if($row['IS_NULLABLE'] == 'NO')
  128. {
  129. $data['rules']['required'][] = $row['COLUMN_NAME'];
  130. }
  131. if(in_array($row['DATA_TYPE'], ['varchar', 'char']))
  132. {
  133. $data['rules']['maxlength'][$row['COLUMN_NAME']] = $row['CHARACTER_MAXIMUM_LENGTH'];
  134. }
  135. if(in_array($row['DATA_TYPE'], ['mediumtext', 'TINYTEXT', 'text', 'longtext']))
  136. {
  137. $data['rules']['text'][] = $row['COLUMN_NAME'];
  138. }
  139. if(in_array($row['DATA_TYPE'], ['bigint', 'int', 'smallint', 'tinyint', 'integer']))
  140. {
  141. preg_match('/[\d]{1,}/', $row['COLUMN_TYPE'], $matches);
  142. $data['rules']['int'][$row['COLUMN_NAME']] = $matches[0];
  143. $data['rules']['number'][] = $row['COLUMN_NAME'];
  144. }
  145. if(in_array($row['DATA_TYPE'], ['float', 'double', 'decimal']))
  146. {
  147. $data['rules']['float'][$row['COLUMN_NAME']] = $this->getValueFromBrackets($row['COLUMN_TYPE']);
  148. }
  149. if(in_array($row['DATA_TYPE'], ['timestamp', 'datatime']))
  150. {
  151. $data['rules']['timestamp'][] = $row['COLUMN_NAME'];
  152. }
  153. if(in_array($row['DATA_TYPE'], ['enum', 'set']))
  154. {
  155. $data['rules']['sets'][$row['COLUMN_NAME']] = $this->getValueFromBrackets($row['COLUMN_TYPE']);
  156. }
  157. if(isset($row['COLUMN_DEFAULT']))
  158. {
  159. $data['rules']['default'][$row['COLUMN_NAME']] = $row['COLUMN_DEFAULT'];
  160. }
  161. }
  162. $data['sql'] = $this->getTableSQL($table, $database);
  163. return $data;
  164. }
  165. /**
  166. * 从括号中获取指定的值
  167. * @param string $str 需要获取的内容
  168. * @return array
  169. */
  170. public function getValueFromBrackets($str)
  171. {
  172. preg_match("/(?:\()(.*)(?:\))/i", $str, $matches);
  173. $str = $matches[1];
  174. $a = explode(",", $str);
  175. for($i=0; $i<count($a); $i++)
  176. {
  177. $this->removeQuote($a[$i]);//从字符串中去除单引号
  178. }
  179. return $a;
  180. }
  181. /**
  182. * 去除双引号
  183. * @param string $str 去除双引号
  184. */
  185. public function removeQuote(&$str)
  186. {
  187. if(preg_match("/^\'/",$str))
  188. {
  189. $str = substr($str, 1, strlen($str)-1);
  190. }
  191. if(preg_match("/\'$/",$str))
  192. {
  193. $str = substr($str, 0, strlen($str)-1);
  194. }
  195. return $str;
  196. }
  197. /**
  198. * 查询数据库中是否有指定的表
  199. * @param string $tableName 表名
  200. * @param null|string $database 数据库
  201. * @return bool
  202. */
  203. public function hasTable($tableName, $database = null)
  204. {
  205. if($database)
  206. {
  207. $this->setQuery('USE '. $database);
  208. }
  209. $sql = "SHOW TABLES LIKE '".$tableName."'";
  210. $rs = $this->setQuery($sql);
  211. $tables = array();
  212. while($row = $this->fetch($rs))
  213. {
  214. if(is_array($row)) {
  215. foreach($row AS $val) {
  216. if($val == $tableName) return true;
  217. }
  218. }
  219. }
  220. return false;
  221. }
  222. /**
  223. * 获取创建表的SQL语句
  224. * @param string $tableName 表名
  225. * @param null|string $database 数据库
  226. * @param int|null $autoIncr 自增长的值,null的话就不使用
  227. * @return string
  228. */
  229. public function getTableSQL($tableName, $database = null, $autoIncr = null)
  230. {
  231. if($database)
  232. {
  233. $this->setQuery('USE '. $database);
  234. }
  235. $row = $this->getRow("SHOW CREATE TABLE `".$tableName."`");
  236. if(!$row) {
  237. throw new \Exception('数据表不存在', __LINE__);
  238. }
  239. $sql = $row['Create Table'];
  240. if($autoIncr === null) {
  241. return $sql;
  242. }
  243. return preg_replace("/AUTO_INCREMENT=[\d]{1,}/", "AUTO_INCREMENT=". intval($autoIncr), $sql);
  244. }
  245. /**
  246. * 通过数据表名称获取规则
  247. * @param string $table 表名
  248. * @param string $database 数据库名
  249. */
  250. public function buildRulesForTable($table, $database = null)
  251. {
  252. if(!$database) $database = $this->currentDB;
  253. $tableInfo = $this->getTableInfo($table, $database);
  254. $rules = new \Qii\Base\Rules();
  255. $rules->addFields($tableInfo['fields']);
  256. if($tableInfo['rules']['required'])
  257. {
  258. $rules->addForceValidKey($tableInfo['rules']['required']);
  259. }
  260. if(isset($tableInfo['rules']['number']))
  261. {
  262. foreach ($tableInfo['rules']['number'] as $key => $value)
  263. {
  264. $rules->addRules($value, 'number', true, $value . '字段必须是数字');
  265. }
  266. }
  267. if(isset($tableInfo['rules']['maxlength']))
  268. {
  269. foreach ($tableInfo['rules']['maxlength'] as $key => $value)
  270. {
  271. $rules->addRules($key, 'maxlength', $value, $key . '字段内容长度不能大于'. $value .'个字符');
  272. }
  273. }
  274. if(isset($tableInfo['rules']['timestamp']))
  275. {
  276. foreach ($tableInfo['rules']['timestamp'] as $key => $value)
  277. {
  278. $rules->addRules($value, 'datetime', true, $value . '字段必须为日期格式');
  279. }
  280. }
  281. return $rules;
  282. }
  283. final public function getAlias($alias)
  284. {
  285. return isset($this->_modelAlias[$alias]) ? $this->_modelAlias[$alias] : null;
  286. }
  287. /**
  288. * 设置Cache
  289. *
  290. * @param String $cache
  291. * @param Array $policy
  292. */
  293. final public function setCache($cache, $policy)
  294. {
  295. \Qii\Autoloader\Import::requires(Qii_DIR . DS . 'Qii' . DS . 'Cache.php');
  296. $this->_cache = \Qii\Autoloader\Psr4::loadClass('\Qii\Cache', $cache)->initialization($policy);//载入cache类文件
  297. }
  298. /**
  299. * 缓存内容
  300. *
  301. * @param String $id
  302. * @param Array $value
  303. * @return Bool
  304. */
  305. final public function cache($id, $value)
  306. {
  307. return $this->_cache->set($id, $value);
  308. }
  309. /**
  310. * 获取缓存的类
  311. */
  312. final public function getCache()
  313. {
  314. return $this->_cache;
  315. }
  316. /**
  317. * 获取缓存内容
  318. *
  319. * @param String $id
  320. * @return Array
  321. */
  322. final public function getCacheData($id)
  323. {
  324. return $this->_cache->get($id);
  325. }
  326. /**
  327. * 获取表的名称
  328. * @param String $table
  329. * @return String
  330. */
  331. public function getTable($table)
  332. {
  333. return $table;
  334. }
  335. public function setLanguage()
  336. {
  337. $this->language = \Qii\Autoloader\Psr4::loadClass('Qii_Language_Loader');
  338. }
  339. /**
  340. *
  341. * Insert Object
  342. * @param String $table
  343. * @param Array|Object $dataArray
  344. */
  345. final function insertObject($table, $dataArray)
  346. {
  347. if (empty($table)) {
  348. return -1;
  349. }
  350. if (sizeof($dataArray) > 0 || (is_object($dataArray) && get_object_vars($dataArray)) > 0) {
  351. $keys = array();
  352. $values = array();
  353. foreach ($dataArray AS $key => $value) {
  354. $keys[] = $key;
  355. if(is_array($value))
  356. {
  357. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  358. }
  359. $values[] = $this->setQuote($value);
  360. }
  361. $this->modelSQL = $sql = "INSERT INTO `{$table}`(`" . join("`, `", $keys) . "`) VALUES('" . join("', '", $values) . "')";
  362. $this->setQuery($sql);
  363. $this->cleanData();
  364. $this->setError();
  365. return $this->lastInsertId();
  366. }
  367. return -2;
  368. }
  369. /**
  370. *
  371. * Replace Object
  372. * @param String $table
  373. * @param Array|Object $dataArray
  374. */
  375. final function replaceObject($table, $dataArray)
  376. {
  377. if (empty($table)) {
  378. return -1;
  379. }
  380. if (sizeof($dataArray) > 0 || get_object_vars($dataArray) > 0) {
  381. $keys = array();
  382. $values = array();
  383. foreach ($dataArray AS $key => $value) {
  384. $keys[] = $key;
  385. if(is_array($value))
  386. {
  387. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  388. }
  389. $values[] = $this->setQuote($value);
  390. }
  391. $this->modelSQL = $sql = "REPLACE INTO `{$table}`(`" . join("`, `", $keys) . "`) VALUES('" . join("', '", $values) . "')";
  392. $rs = $this->setQuery($sql);
  393. $this->cleanData();
  394. $this->setError();
  395. return $this->AffectedRows($rs);
  396. }
  397. return -2;
  398. }
  399. /**
  400. *
  401. * Update data
  402. * @param String $table
  403. * @param Array|Objct $dataArray
  404. * @param Array $keys
  405. */
  406. final function updateObject($table, $dataArray, $keys = array())
  407. {
  408. if (empty($table) || !is_array($keys)) {
  409. return -1;
  410. }
  411. if (sizeof($dataArray) > 0 || get_object_vars($dataArray) > 0) {
  412. $values = array();
  413. $where = array();
  414. foreach ($dataArray AS $key => $value) {
  415. if(is_array($value))
  416. {
  417. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  418. }
  419. $value = $this->setQuote($value);
  420. if (in_array($key, $keys)) {
  421. $where[] = "`{$key}` = '" . $value . "'";
  422. } else {
  423. $values[] = "`{$key}` = '" . $value . "'";
  424. }
  425. }
  426. //$keys为key => value的方式,就直接用keys
  427. if (empty($where) && count($keys) > 0) {
  428. foreach ($keys as $key => $value) {
  429. $value = $this->setQuote($value);
  430. $where[] = "`{$key}` = '" . $value . "'";
  431. }
  432. }
  433. $this->modelSQL = $sql = "UPDATE `{$table}` SET " . join(", ", $values) . (sizeof($where) > 0 ? " WHERE " . join(" AND ", $where) : '');
  434. $rs = $this->setQuery($sql);
  435. $this->cleanData();
  436. $this->setError();
  437. return $this->AffectedRows($rs);
  438. }
  439. return 0;
  440. }
  441. /**
  442. *
  443. * 删除数据
  444. * @param String $table
  445. * @param Array $keys
  446. */
  447. final function deleteObject($table, $keys = array())
  448. {
  449. if (empty($table)) {
  450. return -1;
  451. }
  452. $where = array();
  453. if (sizeof($keys) > 0 || get_object_vars($keys)) {
  454. foreach ($keys AS $k => $v) {
  455. $where[] = "`{$k}` = '" . $this->setQuote($v) . "'";
  456. }
  457. }
  458. $this->modelSQL = $sql = "DELETE FROM `{$table}`" . (sizeof($where) > 0 ? " WHERE " . join(" AND ", $where) : '');
  459. $rs = $this->query($sql);
  460. $this->cleanData();
  461. $this->setError();
  462. return $this->AffectedRows($rs);
  463. }
  464. /**
  465. * 需要清除的数据
  466. *
  467. * @return Array
  468. */
  469. final function cleanOptions()
  470. {
  471. return array('fields', 'where', 'groupBy', 'orderBy', 'limit', 'setArray');
  472. }
  473. /**
  474. * 清除数据
  475. *
  476. */
  477. final function cleanData()
  478. {
  479. $array = $this->cleanOptions();
  480. foreach ($array AS $k) {
  481. if (is_array($this->$k)) {
  482. $this->$k = array();
  483. } else {
  484. $this->$k = null;
  485. }
  486. }
  487. }
  488. /**
  489. *
  490. * 查询的字段
  491. * @param String $fileds
  492. */
  493. final function fields($fileds = "*")
  494. {
  495. $this->fields = null;
  496. if (empty($fileds)) $fileds = "*";
  497. if (is_array($fileds)) $fileds = join(',', $fileds);
  498. $this->fields = $fileds;
  499. return $this;
  500. }
  501. /**
  502. *
  503. * GROUP BY方法
  504. * @param String $fields
  505. */
  506. final function groupBy($fields)
  507. {
  508. $this->groupBy = null;
  509. if (!empty($fields)) {
  510. $this->groupBy = sprintf($this->_query['GROUP'], $fields);
  511. }
  512. return $this;
  513. }
  514. /**
  515. *
  516. * 插入数据用
  517. * @param Array $array
  518. */
  519. final function dataArray($array)
  520. {
  521. $this->fileds = null;
  522. if (is_array($array)) {
  523. $tmpArray = array();
  524. foreach ($array AS $k => $v) {
  525. $tmpArray['k'][] = $k;
  526. $tmpArray['v'][] = $this->setQuote($v);
  527. }
  528. $this->fileds = $tmpArray;
  529. }
  530. return $this;
  531. }
  532. /**
  533. *
  534. * Order By函数
  535. * @param String $field
  536. * @param String $orderBy
  537. */
  538. final function orderBy($field, $orderBy)
  539. {
  540. if(!empty($field)) return $this;
  541. if($this->orderBy != '') {
  542. $this->orderBy .= $field .' '. $orderBy;
  543. }else{
  544. $this->orderBy = sprintf($this->_query['ORDER'], $field, $orderBy);
  545. }
  546. }
  547. final function orderByArr($map)
  548. {
  549. if(empty($map)) return $this;
  550. foreach($map AS $val)
  551. {
  552. $this->orderBy($val['field'], $val['orderBy']);
  553. }
  554. return $this;
  555. }
  556. final function orderByStr($orderBy)
  557. {
  558. if(!$orderBy) return $this;
  559. $this->orderBy = $orderBy;
  560. return $this;
  561. }
  562. /**
  563. *
  564. * Limit函数,如果省略第二个参数则第一个为0,第二个参数值取第一个
  565. * @param Int $limit
  566. * @param Int $offset
  567. */
  568. final function limit($limit, $offset = 0)
  569. {
  570. $this->limit = null;
  571. if ($limit !== '') {
  572. if (!$offset) {
  573. $this->limit = sprintf($this->_query["LIMIT"], 0, $limit);
  574. } else {
  575. $this->limit = sprintf($this->_query["LIMIT"], $limit, $offset);
  576. }
  577. }
  578. return $this;
  579. }
  580. /**
  581. * 传的条件为数组
  582. * @param Array $where 条件
  583. * @return Object 对象本身
  584. */
  585. final function whereArray($where)
  586. {
  587. $this->where = null;
  588. if (!empty($where)) {
  589. $whereArray = array();
  590. foreach ($where AS $k => $v) {
  591. $whereArray[] = " `{$k}` = '{$v}'";
  592. }
  593. if (sizeof($whereArray) > 0) {
  594. $whereSQL = join(" AND ", $whereArray);
  595. $this->where = sprintf($this->_query["WHERE"], $whereSQL);
  596. }
  597. }
  598. return $this;
  599. }
  600. /**
  601. *
  602. * WHERE 子句
  603. * @param String $where
  604. */
  605. final function where($where)
  606. {
  607. if (is_array($where)) return $this->whereArray($where);
  608. $this->where = null;
  609. if (!empty($where)) {
  610. $this->where = sprintf($this->_query["WHERE"], $where);
  611. }
  612. return $this;
  613. }
  614. /**
  615. *
  616. * 插入数据到指定表中
  617. * @param String $table
  618. */
  619. final function insertRow($table)
  620. {
  621. $this->modelSQL = $sql = sprintf($this->_query['INSERT'], $table, join(",", $this->fileds['k']), join("', '", $this->fileds['v']));
  622. $this->cleanData();
  623. $this->setQuery($sql, '');
  624. return $this->lastInsertId();
  625. }
  626. /**
  627. *
  628. * Replace方法
  629. * @param String $table
  630. */
  631. final function replaceRow($table)
  632. {
  633. $this->modelSQL = $sql = sprintf($this->_query['REPLACE'], $table, join(",", $this->fileds['k']), join("', '", $this->fileds['v']));
  634. $this->cleanData();
  635. return $this->exec($sql);
  636. }
  637. /**
  638. *
  639. * 查询一行
  640. * @param String $table
  641. */
  642. final function selectRow($table)
  643. {
  644. $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  645. $this->cleanData();
  646. return $this->getRow($sql);
  647. }
  648. /**
  649. *
  650. * 查询一行
  651. * @param String $table
  652. */
  653. final function selectOne($table)
  654. {
  655. $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  656. $this->cleanData();
  657. return $this->getOne($sql);
  658. }
  659. /**
  660. * 创建SQL
  661. */
  662. final function createSQL($table)
  663. {
  664. $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  665. $this->cleanData();
  666. return $sql;
  667. }
  668. /**
  669. *
  670. * 查询所有
  671. * @param String $table
  672. * @return Array
  673. */
  674. final function selectAll($table)
  675. {
  676. $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  677. $this->cleanData();
  678. return $this->getAll($sql);
  679. }
  680. /**
  681. * 将指定字段减指定值
  682. *
  683. * @param $data
  684. * @return $this
  685. */
  686. final function downsetCounter($data)
  687. {
  688. if (is_array($data)) {
  689. foreach ($data AS $k => $value) {
  690. $this->setArray[] = $k . "=" . $k . '-' . $value;
  691. }
  692. }
  693. $this->set(null);
  694. return $this;
  695. }
  696. /**
  697. * 将指定字段加指定值
  698. *
  699. * @param $data
  700. * @return $this
  701. */
  702. final function upsetCounter($data)
  703. {
  704. if (is_array($data)) {
  705. foreach ($data AS $k => $value) {
  706. $this->setArray[] = $k . "=" . $k . '+' . $value;
  707. }
  708. }
  709. $this->set(null);
  710. return $this;
  711. }
  712. /**
  713. * 更新数据时候用,方法同setData
  714. * @param Array $data
  715. */
  716. final function set($data)
  717. {
  718. return $this->setData($data);
  719. }
  720. /**
  721. *
  722. * 更新数据时候用
  723. * @param Array $data
  724. * @return $this
  725. */
  726. final function setData($data)
  727. {
  728. if (is_array($data)) {
  729. $set = array();
  730. foreach ($data AS $k => $value) {
  731. $set[] = $k . "='" . $this->setQuote($value) . "'";
  732. }
  733. if (sizeof($this->setArray) > 0) {
  734. $this->set = " " . join(", ", $set) . ", " . join(",", $this->setArray);
  735. } else {
  736. $this->set = " " . join(", ", $set);
  737. }
  738. } else {
  739. if (sizeof($this->setArray) > 0) {
  740. $this->set = join(",", $this->setArray);
  741. } else {
  742. $this->set = "";
  743. }
  744. }
  745. return $this;
  746. }
  747. /**
  748. * 执行更新操作,updateRows的alias
  749. * @param String $table
  750. * @return number
  751. */
  752. /*
  753. final function update($table){
  754. return $this->updateRows($table);
  755. }
  756. */
  757. /**
  758. *
  759. * 执行更新操作
  760. * @param $table
  761. * @return Int 返回影响的行数
  762. */
  763. final function updateRows($table)
  764. {
  765. $this->modelSQL = $sql = sprintf($this->_query['UPDATE'], $table) . $this->set . $this->where . $this->limit;
  766. $this->cleanData();
  767. return $this->exec($sql);
  768. }
  769. /**
  770. *
  771. * 执行删除操作
  772. * @param String $table
  773. */
  774. final function deleteRows($table)
  775. {
  776. $this->modelSQL = $sql = sprintf($this->_query['DELETE'], $table, $this->where) . $this->limit;
  777. $this->cleanData();
  778. return $this->exec($sql);
  779. }
  780. /**
  781. * 执行Model过程中保存的相关信息
  782. *
  783. * @param String $option
  784. * @return Mix
  785. */
  786. final function querySQL($option = '')
  787. {
  788. $allow = array('_queryTimes', '_querySeconds', '_errorInfo', '_exeSQL');
  789. if (in_array($option, $allow)) {
  790. return $this->{$option};
  791. }
  792. return 0;
  793. }
  794. /**
  795. * 将结果编码一下
  796. * @param String $word
  797. * @return String|multitype:
  798. */
  799. public function setQuote($word)//过滤sql字符
  800. {
  801. if (ini_get("magic_quotes_gpc")) {
  802. return $word;
  803. }
  804. return is_array($word) ? array_map('addslashes', $word) : addslashes($word);
  805. }
  806. /**
  807. * 获取错误码
  808. */
  809. public function getCode()
  810. {
  811. return $this->_response->getCode();
  812. }
  813. /**
  814. * 获取错误信息
  815. */
  816. public function getMessage()
  817. {
  818. if($this->_response->isError())
  819. {
  820. return $this->_response->getMessage();
  821. }
  822. }
  823. /**
  824. * 返回response对象
  825. *
  826. * @return Bool
  827. */
  828. public function getResponse()
  829. {
  830. return $this->_response;
  831. }
  832. public function iconv($str)
  833. {
  834. if (is_array($str)) {
  835. return array_map(function ($n) {
  836. return iconv('GB2312', 'UTF-8', $n);
  837. }, $str);
  838. }
  839. return iconv('GB2312', 'UTF-8', $str);
  840. }
  841. /**
  842. * 如果不存在指定的方法则调用提示错误
  843. *
  844. * @param String $name
  845. * @param Mix $args
  846. * @return Mix
  847. */
  848. public function __call($method, $argvs)
  849. {
  850. if (isset($this->_modelAlias[$method])) {
  851. if (method_exists($this, $this->_modelAlias[$method])) {
  852. return call_user_func_array(array($this, $this->_modelAlias[$method]), $argvs);
  853. }
  854. \Qii::setError(false, __LINE__, 1506, 'Alias ' . get_called_class() . '->' . $method . '()');
  855. }
  856. \Qii::setError(false, __LINE__, 1506, get_called_class() . '->' . $method . '()');
  857. }
  858. }