Query.php 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\db;
  12. use PDO;
  13. use think\Cache;
  14. use think\Collection;
  15. use think\Config;
  16. use think\Db;
  17. use think\Data;
  18. use think\db\exception\BindParamException;
  19. use think\db\exception\DataNotFoundException;
  20. use think\db\exception\ModelNotFoundException;
  21. use think\Exception;
  22. use think\exception\DbException;
  23. use think\exception\PDOException;
  24. use think\Loader;
  25. use think\Model;
  26. use think\model\Relation;
  27. use think\model\relation\OneToOne;
  28. use think\Paginator;
  29. class Query
  30. {
  31. // 数据库Connection对象实例
  32. protected $connection;
  33. // 数据库Builder对象实例
  34. protected $builder;
  35. // 当前模型类名称
  36. protected $model;
  37. // 当前数据表名称(含前缀)
  38. protected $table = '';
  39. // 当前数据表名称(不含前缀)
  40. protected $name = '';
  41. // 当前数据表主键
  42. protected $pk;
  43. // 当前数据表前缀
  44. protected $prefix = '';
  45. // 查询参数
  46. protected $options = [];
  47. // 参数绑定
  48. protected $bind = [];
  49. // 数据表信息
  50. protected static $info = [];
  51. // 回调事件
  52. private static $event = [];
  53. /**
  54. * 架构函数
  55. * @access public
  56. * @param Connection $connection 数据库对象实例
  57. * @param string $model 模型名
  58. */
  59. public function __construct(Connection $connection = null, $model = '')
  60. {
  61. $this->connection = $connection ?: Db::connect([], true);
  62. $this->prefix = $this->connection->getConfig('prefix');
  63. $this->model = $model;
  64. // 设置当前连接的Builder对象
  65. $this->setBuilder();
  66. }
  67. /**
  68. * 利用__call方法实现一些特殊的Model方法
  69. * @access public
  70. * @param string $method 方法名称
  71. * @param array $args 调用参数
  72. * @return mixed
  73. * @throws DbException
  74. * @throws Exception
  75. */
  76. public function __call($method, $args)
  77. {
  78. if (strtolower(substr($method, 0, 5)) == 'getby') {
  79. // 根据某个字段获取记录
  80. $field = Loader::parseName(substr($method, 5));
  81. $where[$field] = $args[0];
  82. return $this->where($where)->find();
  83. } elseif (strtolower(substr($method, 0, 10)) == 'getfieldby') {
  84. // 根据某个字段获取记录的某个值
  85. $name = Loader::parseName(substr($method, 10));
  86. $where[$name] = $args[0];
  87. return $this->where($where)->value($args[1]);
  88. } else {
  89. throw new Exception('method not exist:' . __CLASS__ . '->' . $method);
  90. }
  91. }
  92. /**
  93. * 获取当前的数据库Connection对象
  94. * @access public
  95. * @return Connection
  96. */
  97. public function getConnection()
  98. {
  99. return $this->connection;
  100. }
  101. /**
  102. * 切换当前的数据库连接
  103. * @access public
  104. * @param mixed $config
  105. * @return $this
  106. */
  107. public function connect($config)
  108. {
  109. $this->connection = Db::connect($config);
  110. $this->setBuilder();
  111. return $this;
  112. }
  113. /**
  114. * 设置当前的数据库Builder对象
  115. * @access protected
  116. * @return void
  117. */
  118. protected function setBuilder()
  119. {
  120. $builder = $this->connection->getConfig('builder') ?: $this->connection->getConfig('type');
  121. $class = false !== strpos($builder, '\\') ? $builder : '\\think\\db\\builder\\' . ucfirst($builder);
  122. $this->builder = new $class($this->connection, $this);
  123. }
  124. /**
  125. * 获取当前的模型对象名
  126. * @access public
  127. * @return string
  128. */
  129. public function getModel()
  130. {
  131. return $this->model;
  132. }
  133. /**
  134. * 获取当前的builder实例对象
  135. * @access public
  136. * @return Builder
  137. */
  138. public function getBuilder()
  139. {
  140. return $this->builder;
  141. }
  142. /**
  143. * 指定默认的数据表名(不含前缀)
  144. * @access public
  145. * @param string $name
  146. * @return $this
  147. */
  148. public function name($name)
  149. {
  150. $this->name = $name;
  151. return $this;
  152. }
  153. /**
  154. * 指定默认数据表名(含前缀)
  155. * @access public
  156. * @param string $table 表名
  157. * @return $this
  158. */
  159. public function setTable($table)
  160. {
  161. $this->table = $table;
  162. return $this;
  163. }
  164. /**
  165. * 得到当前或者指定名称的数据表
  166. * @access public
  167. * @param string $name
  168. * @return string
  169. */
  170. public function getTable($name = '')
  171. {
  172. if ($name || empty($this->table)) {
  173. $name = $name ?: $this->name;
  174. $tableName = $this->prefix;
  175. if ($name) {
  176. $tableName .= Loader::parseName($name);
  177. }
  178. } else {
  179. $tableName = $this->table;
  180. }
  181. return $tableName;
  182. }
  183. /**
  184. * 将SQL语句中的__TABLE_NAME__字符串替换成带前缀的表名(小写)
  185. * @access public
  186. * @param string $sql sql语句
  187. * @return string
  188. */
  189. public function parseSqlTable($sql)
  190. {
  191. if (false !== strpos($sql, '__')) {
  192. $prefix = $this->prefix;
  193. $sql = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {
  194. return $prefix . strtolower($match[1]);
  195. }, $sql);
  196. }
  197. return $sql;
  198. }
  199. /**
  200. * 执行查询 返回数据集
  201. * @access public
  202. * @param string $sql sql指令
  203. * @param array $bind 参数绑定
  204. * @param boolean $master 是否在主服务器读操作
  205. * @param bool|string $class 指定返回的数据集对象
  206. * @return mixed
  207. * @throws BindParamException
  208. * @throws PDOException
  209. */
  210. public function query($sql, $bind = [], $master = false, $class = false)
  211. {
  212. return $this->connection->query($sql, $bind, $master, $class);
  213. }
  214. /**
  215. * 执行语句
  216. * @access public
  217. * @param string $sql sql指令
  218. * @param array $bind 参数绑定
  219. * @return int
  220. * @throws BindParamException
  221. * @throws PDOException
  222. */
  223. public function execute($sql, $bind = [])
  224. {
  225. return $this->connection->execute($sql, $bind);
  226. }
  227. /**
  228. * 获取最近插入的ID
  229. * @access public
  230. * @param string $sequence 自增序列名
  231. * @return string
  232. */
  233. public function getLastInsID($sequence = null)
  234. {
  235. return $this->connection->getLastInsID($sequence);
  236. }
  237. /**
  238. * 获取最近一次查询的sql语句
  239. * @access public
  240. * @return string
  241. */
  242. public function getLastSql()
  243. {
  244. return $this->connection->getLastSql();
  245. }
  246. /**
  247. * 执行数据库事务
  248. * @access public
  249. * @param callable $callback 数据操作方法回调
  250. * @return mixed
  251. */
  252. public function transaction($callback)
  253. {
  254. return $this->connection->transaction($callback);
  255. }
  256. /**
  257. * 启动事务
  258. * @access public
  259. * @return void
  260. */
  261. public function startTrans()
  262. {
  263. $this->connection->startTrans();
  264. }
  265. /**
  266. * 用于非自动提交状态下面的查询提交
  267. * @access public
  268. * @return void
  269. * @throws PDOException
  270. */
  271. public function commit()
  272. {
  273. $this->connection->commit();
  274. }
  275. /**
  276. * 事务回滚
  277. * @access public
  278. * @return void
  279. * @throws PDOException
  280. */
  281. public function rollback()
  282. {
  283. $this->connection->rollback();
  284. }
  285. /**
  286. * 批处理执行SQL语句
  287. * 批处理的指令都认为是execute操作
  288. * @access public
  289. * @param array $sql SQL批处理指令
  290. * @return boolean
  291. */
  292. public function batchQuery($sql = [])
  293. {
  294. return $this->connection->batchQuery($sql);
  295. }
  296. /**
  297. * 获取数据库的配置参数
  298. * @access public
  299. * @param string $name 参数名称
  300. * @return boolean
  301. */
  302. public function getConfig($name = '')
  303. {
  304. return $this->connection->getConfig($name);
  305. }
  306. /**
  307. * 得到分表的的数据表名
  308. * @access public
  309. * @param array $data 操作的数据
  310. * @param string $field 分表依据的字段
  311. * @param array $rule 分表规则
  312. * @return string
  313. */
  314. public function getPartitionTableName($data, $field, $rule = [])
  315. {
  316. // 对数据表进行分区
  317. if ($field && isset($data[$field])) {
  318. $value = $data[$field];
  319. $type = $rule['type'];
  320. switch ($type) {
  321. case 'id':
  322. // 按照id范围分表
  323. $step = $rule['expr'];
  324. $seq = floor($value / $step) + 1;
  325. break;
  326. case 'year':
  327. // 按照年份分表
  328. if (!is_numeric($value)) {
  329. $value = strtotime($value);
  330. }
  331. $seq = date('Y', $value) - $rule['expr'] + 1;
  332. break;
  333. case 'mod':
  334. // 按照id的模数分表
  335. $seq = ($value % $rule['num']) + 1;
  336. break;
  337. case 'md5':
  338. // 按照md5的序列分表
  339. $seq = (ord(substr(md5($value), 0, 1)) % $rule['num']) + 1;
  340. break;
  341. default:
  342. if (function_exists($type)) {
  343. // 支持指定函数哈希
  344. $seq = (ord(substr($type($value), 0, 1)) % $rule['num']) + 1;
  345. } else {
  346. // 按照字段的首字母的值分表
  347. $seq = (ord($value{0}) % $rule['num']) + 1;
  348. }
  349. }
  350. return $this->getTable() . '_' . $seq;
  351. } else {
  352. // 当设置的分表字段不在查询条件或者数据中
  353. // 进行联合查询,必须设定 partition['num']
  354. $tableName = [];
  355. for ($i = 0; $i < $rule['num']; $i++) {
  356. $tableName[] = 'SELECT * FROM ' . $this->getTable() . '_' . ($i + 1);
  357. }
  358. $tableName = '( ' . implode(" UNION ", $tableName) . ') AS ' . $this->name;
  359. return $tableName;
  360. }
  361. }
  362. /**
  363. * 得到某个字段的值
  364. * @access public
  365. * @param string $field 字段名
  366. * @param mixed $default 默认值
  367. * @param bool $force 强制转为数字类型
  368. * @return mixed
  369. */
  370. public function value($field, $default = null, $force = false)
  371. {
  372. $result = false;
  373. if (empty($options['fetch_sql']) && !empty($this->options['cache'])) {
  374. // 判断查询缓存
  375. $cache = $this->options['cache'];
  376. if (empty($this->options['table'])) {
  377. $this->options['table'] = $this->getTable();
  378. }
  379. $key = is_string($cache['key']) ? $cache['key'] : md5($field . serialize($this->options));
  380. $result = Cache::get($key);
  381. }
  382. if (false === $result) {
  383. if (isset($this->options['field'])) {
  384. unset($this->options['field']);
  385. }
  386. $pdo = $this->field($field)->limit(1)->getPdo();
  387. if (is_string($pdo)) {
  388. // 返回SQL语句
  389. return $pdo;
  390. }
  391. $result = $pdo->fetchColumn();
  392. if ($force) {
  393. $result = is_numeric($result) ? $result + 0 : $result;
  394. }
  395. if (isset($cache)) {
  396. // 缓存数据
  397. if (isset($cache['tag'])) {
  398. Cache::tag($cache['tag'])->set($key, $result, $cache['expire']);
  399. } else {
  400. Cache::set($key, $result, $cache['expire']);
  401. }
  402. }
  403. } else {
  404. // 清空查询条件
  405. $this->options = [];
  406. }
  407. return false !== $result ? $result : $default;
  408. }
  409. /**
  410. * 得到某个列的数组
  411. * @access public
  412. * @param string $field 字段名 多个字段用逗号分隔
  413. * @param string $key 索引
  414. * @return array
  415. */
  416. public function column($field, $key = '')
  417. {
  418. $result = false;
  419. if (empty($options['fetch_sql']) && !empty($this->options['cache'])) {
  420. // 判断查询缓存
  421. $cache = $this->options['cache'];
  422. if (empty($this->options['table'])) {
  423. $this->options['table'] = $this->getTable();
  424. }
  425. $guid = is_string($cache['key']) ? $cache['key'] : md5($field . serialize($this->options));
  426. $result = Cache::get($guid);
  427. }
  428. if (false === $result) {
  429. if (isset($this->options['field'])) {
  430. unset($this->options['field']);
  431. }
  432. if ($key && '*' != $field) {
  433. $field = $key . ',' . $field;
  434. }
  435. $pdo = $this->field($field)->getPdo();
  436. if (is_string($pdo)) {
  437. // 返回SQL语句
  438. return $pdo;
  439. }
  440. if (1 == $pdo->columnCount()) {
  441. $result = $pdo->fetchAll(PDO::FETCH_COLUMN);
  442. } else {
  443. $resultSet = $pdo->fetchAll(PDO::FETCH_ASSOC);
  444. if ($resultSet) {
  445. $fields = array_keys($resultSet[0]);
  446. $count = count($fields);
  447. $key1 = array_shift($fields);
  448. $key2 = $fields ? array_shift($fields) : '';
  449. $key = $key ?: $key1;
  450. if (strpos($key, '.')) {
  451. list($alias, $key) = explode('.', $key);
  452. }
  453. foreach ($resultSet as $val) {
  454. if ($count > 2) {
  455. $result[$val[$key]] = $val;
  456. } elseif (2 == $count) {
  457. $result[$val[$key]] = $val[$key2];
  458. } elseif (1 == $count) {
  459. $result[$val[$key]] = $val[$key1];
  460. }
  461. }
  462. } else {
  463. $result = [];
  464. }
  465. }
  466. if (isset($cache) && isset($guid)) {
  467. // 缓存数据
  468. if (isset($cache['tag'])) {
  469. Cache::tag($cache['tag'])->set($guid, $result, $cache['expire']);
  470. } else {
  471. Cache::set($guid, $result, $cache['expire']);
  472. }
  473. }
  474. } else {
  475. // 清空查询条件
  476. $this->options = [];
  477. }
  478. return $result;
  479. }
  480. /**
  481. * COUNT查询
  482. * @access public
  483. * @param string $field 字段名
  484. * @return integer|string
  485. */
  486. public function count($field = '*')
  487. {
  488. if (isset($this->options['group'])) {
  489. // 支持GROUP
  490. $options = $this->getOptions();
  491. $subSql = $this->options($options)->field('count(' . $field . ')')->bind($this->bind)->buildSql();
  492. return $this->table([$subSql => '_group_count_'])->value('COUNT(*) AS tp_count', 0, true);
  493. }
  494. return $this->value('COUNT(' . $field . ') AS tp_count', 0, true);
  495. }
  496. /**
  497. * SUM查询
  498. * @access public
  499. * @param string $field 字段名
  500. * @return float|int
  501. */
  502. public function sum($field)
  503. {
  504. return $this->value('SUM(' . $field . ') AS tp_sum', 0, true);
  505. }
  506. /**
  507. * MIN查询
  508. * @access public
  509. * @param string $field 字段名
  510. * @return mixed
  511. */
  512. public function min($field)
  513. {
  514. return $this->value('MIN(' . $field . ') AS tp_min', 0, true);
  515. }
  516. /**
  517. * MAX查询
  518. * @access public
  519. * @param string $field 字段名
  520. * @return mixed
  521. */
  522. public function max($field)
  523. {
  524. return $this->value('MAX(' . $field . ') AS tp_max', 0, true);
  525. }
  526. /**
  527. * AVG查询
  528. * @access public
  529. * @param string $field 字段名
  530. * @return float|int
  531. */
  532. public function avg($field)
  533. {
  534. return $this->value('AVG(' . $field . ') AS tp_avg', 0, true);
  535. }
  536. /**
  537. * 设置记录的某个字段值
  538. * 支持使用数据库字段和方法
  539. * @access public
  540. * @param string|array $field 字段名
  541. * @param mixed $value 字段值
  542. * @return integer
  543. */
  544. public function setField($field, $value = '')
  545. {
  546. if (is_array($field)) {
  547. $data = $field;
  548. } else {
  549. $data[$field] = $value;
  550. }
  551. return $this->update($data);
  552. }
  553. /**
  554. * 字段值(延迟)增长
  555. * @access public
  556. * @param string $field 字段名
  557. * @param integer $step 增长值
  558. * @param integer $lazyTime 延时时间(s)
  559. * @return integer|true
  560. * @throws Exception
  561. */
  562. public function setInc($field, $step = 1, $lazyTime = 0)
  563. {
  564. $condition = !empty($this->options['where']) ? $this->options['where'] : [];
  565. if (empty($condition)) {
  566. // 没有条件不做任何更新
  567. throw new Exception('no data to update');
  568. }
  569. if ($lazyTime > 0) {
  570. // 延迟写入
  571. $guid = md5($this->getTable() . '_' . $field . '_' . serialize($condition));
  572. $step = $this->lazyWrite('inc', $guid, $step, $lazyTime);
  573. if (false === $step) {
  574. // 清空查询条件
  575. $this->options = [];
  576. return true;
  577. }
  578. }
  579. return $this->setField($field, ['exp', $field . '+' . $step]);
  580. }
  581. /**
  582. * 字段值(延迟)减少
  583. * @access public
  584. * @param string $field 字段名
  585. * @param integer $step 减少值
  586. * @param integer $lazyTime 延时时间(s)
  587. * @return integer|true
  588. * @throws Exception
  589. */
  590. public function setDec($field, $step = 1, $lazyTime = 0)
  591. {
  592. $condition = !empty($this->options['where']) ? $this->options['where'] : [];
  593. if (empty($condition)) {
  594. // 没有条件不做任何更新
  595. throw new Exception('no data to update');
  596. }
  597. if ($lazyTime > 0) {
  598. // 延迟写入
  599. $guid = md5($this->getTable() . '_' . $field . '_' . serialize($condition));
  600. $step = $this->lazyWrite('dec', $guid, $step, $lazyTime);
  601. if (false === $step) {
  602. // 清空查询条件
  603. $this->options = [];
  604. return true;
  605. }
  606. }
  607. return $this->setField($field, ['exp', $field . '-' . $step]);
  608. }
  609. /**
  610. * 延时更新检查 返回false表示需要延时
  611. * 否则返回实际写入的数值
  612. * @access protected
  613. * @param string $type 自增或者自减
  614. * @param string $guid 写入标识
  615. * @param integer $step 写入步进值
  616. * @param integer $lazyTime 延时时间(s)
  617. * @return false|integer
  618. */
  619. protected function lazyWrite($type, $guid, $step, $lazyTime)
  620. {
  621. if (!Cache::has($guid . '_time')) {
  622. // 计时开始
  623. Cache::set($guid . '_time', $_SERVER['REQUEST_TIME'], 0);
  624. Cache::$type($guid, $step, 0);
  625. } elseif ($_SERVER['REQUEST_TIME'] > Cache::get($guid . '_time') + $lazyTime) {
  626. // 删除缓存
  627. $value = Cache::$type($guid, $step, 0);
  628. Cache::rm($guid);
  629. Cache::rm($guid . '_time');
  630. return 0 === $value ? false : $value;
  631. } else {
  632. // 更新缓存
  633. Cache::$type($guid, $step, 0);
  634. }
  635. return false;
  636. }
  637. /**
  638. * 查询SQL组装 join
  639. * @access public
  640. * @param mixed $join 关联的表名
  641. * @param mixed $condition 条件
  642. * @param string $type JOIN类型
  643. * @return $this
  644. */
  645. public function join($join, $condition = null, $type = 'INNER')
  646. {
  647. if (empty($condition)) {
  648. // 如果为组数,则循环调用join
  649. foreach ($join as $key => $value) {
  650. if (is_array($value) && 2 <= count($value)) {
  651. $this->join($value[0], $value[1], isset($value[2]) ? $value[2] : $type);
  652. }
  653. }
  654. } else {
  655. $table = $this->getJoinTable($join);
  656. $this->options['join'][] = [$table, strtoupper($type), $condition];
  657. }
  658. return $this;
  659. }
  660. /**
  661. * 获取Join表名及别名 支持
  662. * ['prefix_table或者子查询'=>'alias'] 'prefix_table alias' 'table alias'
  663. * @access public
  664. * @param array|string $join
  665. * @return array|string
  666. */
  667. protected function getJoinTable($join, &$alias = null)
  668. {
  669. // 传入的表名为数组
  670. if (is_array($join)) {
  671. // 再php7+版本以上,each()方法被废除
  672. // list($table, $alias) = each($join);
  673. foreach ($join as $key=>$val){
  674. $table = $key;
  675. $alias = $val;
  676. }
  677. } else {
  678. $join = trim($join);
  679. if (false !== strpos($join, '(')) {
  680. // 使用子查询
  681. $table = $join;
  682. } else {
  683. $prefix = $this->prefix;
  684. if (strpos($join, ' ')) {
  685. // 使用别名
  686. list($table, $alias) = explode(' ', $join);
  687. } else {
  688. $table = $join;
  689. if (false === strpos($join, '.') && 0 !== strpos($join, '__')) {
  690. $alias = $join;
  691. }
  692. }
  693. if ($prefix && false === strpos($table, '.') && 0 !== strpos($table, $prefix) && 0 !== strpos($table, '__')) {
  694. $table = $this->getTable($table);
  695. }
  696. }
  697. }
  698. if (isset($alias)) {
  699. if (isset($this->options['alias'][$table])) {
  700. $table = $table . '@think' . uniqid();
  701. }
  702. $table = [$table => $alias];
  703. $this->alias($table);
  704. }
  705. return $table;
  706. }
  707. /**
  708. * 查询SQL组装 union
  709. * @access public
  710. * @param mixed $union
  711. * @param boolean $all
  712. * @return $this
  713. */
  714. public function union($union, $all = false)
  715. {
  716. $this->options['union']['type'] = $all ? 'UNION ALL' : 'UNION';
  717. if (is_array($union)) {
  718. $this->options['union'] = array_merge($this->options['union'], $union);
  719. } else {
  720. $this->options['union'][] = $union;
  721. }
  722. return $this;
  723. }
  724. /**
  725. * 指定查询字段 支持字段排除和指定数据表
  726. * @access public
  727. * @param mixed $field
  728. * @param boolean $except 是否排除
  729. * @param string $tableName 数据表名
  730. * @param string $prefix 字段前缀
  731. * @param string $alias 别名前缀
  732. * @return $this
  733. */
  734. public function field($field, $except = false, $tableName = '', $prefix = '', $alias = '')
  735. {
  736. if (empty($field)) {
  737. return $this;
  738. }
  739. if (is_string($field)) {
  740. $field = array_map('trim', explode(',', $field));
  741. }
  742. if (true === $field) {
  743. // 获取全部字段
  744. $fields = $this->getTableInfo($tableName ?: (isset($this->options['table']) ? $this->options['table'] : ''), 'fields');
  745. $field = $fields ?: ['*'];
  746. } elseif ($except) {
  747. // 字段排除
  748. $fields = $this->getTableInfo($tableName ?: (isset($this->options['table']) ? $this->options['table'] : ''), 'fields');
  749. $field = $fields ? array_diff($fields, $field) : $field;
  750. }
  751. if ($tableName) {
  752. // 添加统一的前缀
  753. $prefix = $prefix ?: $tableName;
  754. foreach ($field as $key => $val) {
  755. if (is_numeric($key)) {
  756. $val = $prefix . '.' . $val . ($alias ? ' AS ' . $alias . $val : '');
  757. }
  758. $field[$key] = $val;
  759. }
  760. }
  761. if (isset($this->options['field'])) {
  762. $field = array_merge($this->options['field'], $field);
  763. }
  764. $this->options['field'] = array_unique($field);
  765. return $this;
  766. }
  767. /**
  768. * 设置数据
  769. * @access public
  770. * @param mixed $field 字段名或者数据
  771. * @param mixed $value 字段值
  772. * @return $this
  773. */
  774. public function data($field, $value = null)
  775. {
  776. if (is_array($field)) {
  777. $this->options['data'] = isset($this->options['data']) ? array_merge($this->options['data'], $field) : $field;
  778. } else {
  779. $this->options['data'][$field] = $value;
  780. }
  781. return $this;
  782. }
  783. /**
  784. * 字段值增长
  785. * @access public
  786. * @param string|array $field 字段名
  787. * @param integer $step 增长值
  788. * @return $this
  789. */
  790. public function inc($field, $step = 1)
  791. {
  792. $fields = is_string($field) ? explode(',', $field) : $field;
  793. foreach ($fields as $field) {
  794. $this->data($field, ['exp', $field . '+' . $step]);
  795. }
  796. return $this;
  797. }
  798. /**
  799. * 字段值减少
  800. * @access public
  801. * @param string|array $field 字段名
  802. * @param integer $step 增长值
  803. * @return $this
  804. */
  805. public function dec($field, $step = 1)
  806. {
  807. $fields = is_string($field) ? explode(',', $field) : $field;
  808. foreach ($fields as $field) {
  809. $this->data($field, ['exp', $field . '-' . $step]);
  810. }
  811. return $this;
  812. }
  813. /**
  814. * 使用表达式设置数据
  815. * @access public
  816. * @param string $field 字段名
  817. * @param string $value 字段值
  818. * @return $this
  819. */
  820. public function exp($field, $value)
  821. {
  822. $this->data($field, ['exp', $value]);
  823. return $this;
  824. }
  825. /**
  826. * 指定JOIN查询字段
  827. * @access public
  828. * @param string|array $table 数据表
  829. * @param string|array $field 查询字段
  830. * @param string|array $on JOIN条件
  831. * @param string $type JOIN类型
  832. * @return $this
  833. */
  834. public function view($join, $field = true, $on = null, $type = 'INNER')
  835. {
  836. $this->options['view'] = true;
  837. if (is_array($join) && is_null($field)) {
  838. foreach ($join as $key => $val) {
  839. $this->view($key, $val[0], isset($val[1]) ? $val[1] : null, isset($val[2]) ? $val[2] : 'INNER');
  840. }
  841. } else {
  842. $fields = [];
  843. $table = $this->getJoinTable($join, $alias);
  844. if (true === $field) {
  845. $fields = $alias . '.*';
  846. } else {
  847. if (is_string($field)) {
  848. $field = explode(',', $field);
  849. }
  850. foreach ($field as $key => $val) {
  851. if (is_numeric($key)) {
  852. $fields[] = $alias . '.' . $val;
  853. $this->options['map'][$val] = $alias . '.' . $val;
  854. } else {
  855. if (preg_match('/[,=\.\'\"\(\s]/', $key)) {
  856. $name = $key;
  857. } else {
  858. $name = $alias . '.' . $key;
  859. }
  860. $fields[] = $name . ' AS ' . $val;
  861. $this->options['map'][$val] = $name;
  862. }
  863. }
  864. }
  865. $this->field($fields);
  866. if ($on) {
  867. $this->join($table, $on, $type);
  868. } else {
  869. $this->table($table);
  870. }
  871. }
  872. return $this;
  873. }
  874. /**
  875. * 设置分表规则
  876. * @access public
  877. * @param array $data 操作的数据
  878. * @param string $field 分表依据的字段
  879. * @param array $rule 分表规则
  880. * @return $this
  881. */
  882. public function partition($data, $field, $rule = [])
  883. {
  884. $this->options['table'] = $this->getPartitionTableName($data, $field, $rule);
  885. return $this;
  886. }
  887. /**
  888. * 指定AND查询条件
  889. * @access public
  890. * @param mixed $field 查询字段
  891. * @param mixed $op 查询表达式
  892. * @param mixed $condition 查询条件
  893. * @return $this
  894. */
  895. public function where($field, $op = null, $condition = null)
  896. {
  897. $param = func_get_args();
  898. array_shift($param);
  899. $this->parseWhereExp('AND', $field, $op, $condition, $param);
  900. return $this;
  901. }
  902. /**
  903. * 指定OR查询条件
  904. * @access public
  905. * @param mixed $field 查询字段
  906. * @param mixed $op 查询表达式
  907. * @param mixed $condition 查询条件
  908. * @return $this
  909. */
  910. public function whereOr($field, $op = null, $condition = null)
  911. {
  912. $param = func_get_args();
  913. array_shift($param);
  914. $this->parseWhereExp('OR', $field, $op, $condition, $param);
  915. return $this;
  916. }
  917. /**
  918. * 指定XOR查询条件
  919. * @access public
  920. * @param mixed $field 查询字段
  921. * @param mixed $op 查询表达式
  922. * @param mixed $condition 查询条件
  923. * @return $this
  924. */
  925. public function whereXor($field, $op = null, $condition = null)
  926. {
  927. $param = func_get_args();
  928. array_shift($param);
  929. $this->parseWhereExp('XOR', $field, $op, $condition, $param);
  930. return $this;
  931. }
  932. /**
  933. * 指定Null查询条件
  934. * @access public
  935. * @param mixed $field 查询字段
  936. * @param string $logic 查询逻辑 and or xor
  937. * @return $this
  938. */
  939. public function whereNull($field, $logic = 'AND')
  940. {
  941. $this->parseWhereExp($logic, $field, 'null', null);
  942. return $this;
  943. }
  944. /**
  945. * 指定NotNull查询条件
  946. * @access public
  947. * @param mixed $field 查询字段
  948. * @param string $logic 查询逻辑 and or xor
  949. * @return $this
  950. */
  951. public function whereNotNull($field, $logic = 'AND')
  952. {
  953. $this->parseWhereExp($logic, $field, 'notnull', null);
  954. return $this;
  955. }
  956. /**
  957. * 指定Exists查询条件
  958. * @access public
  959. * @param mixed $condition 查询条件
  960. * @param string $logic 查询逻辑 and or xor
  961. * @return $this
  962. */
  963. public function whereExists($condition, $logic = 'AND')
  964. {
  965. $this->options['where'][strtoupper($logic)][] = ['exists', $condition];
  966. return $this;
  967. }
  968. /**
  969. * 指定NotExists查询条件
  970. * @access public
  971. * @param mixed $condition 查询条件
  972. * @param string $logic 查询逻辑 and or xor
  973. * @return $this
  974. */
  975. public function whereNotExists($condition, $logic = 'AND')
  976. {
  977. $this->options['where'][strtoupper($logic)][] = ['not exists', $condition];
  978. return $this;
  979. }
  980. /**
  981. * 指定In查询条件
  982. * @access public
  983. * @param mixed $field 查询字段
  984. * @param mixed $condition 查询条件
  985. * @param string $logic 查询逻辑 and or xor
  986. * @return $this
  987. */
  988. public function whereIn($field, $condition, $logic = 'AND')
  989. {
  990. $this->parseWhereExp($logic, $field, 'in', $condition);
  991. return $this;
  992. }
  993. /**
  994. * 指定NotIn查询条件
  995. * @access public
  996. * @param mixed $field 查询字段
  997. * @param mixed $condition 查询条件
  998. * @param string $logic 查询逻辑 and or xor
  999. * @return $this
  1000. */
  1001. public function whereNotIn($field, $condition, $logic = 'AND')
  1002. {
  1003. $this->parseWhereExp($logic, $field, 'not in', $condition);
  1004. return $this;
  1005. }
  1006. /**
  1007. * 指定Like查询条件
  1008. * @access public
  1009. * @param mixed $field 查询字段
  1010. * @param mixed $condition 查询条件
  1011. * @param string $logic 查询逻辑 and or xor
  1012. * @return $this
  1013. */
  1014. public function whereLike($field, $condition, $logic = 'AND')
  1015. {
  1016. $this->parseWhereExp($logic, $field, 'like', $condition);
  1017. return $this;
  1018. }
  1019. /**
  1020. * 指定NotLike查询条件
  1021. * @access public
  1022. * @param mixed $field 查询字段
  1023. * @param mixed $condition 查询条件
  1024. * @param string $logic 查询逻辑 and or xor
  1025. * @return $this
  1026. */
  1027. public function whereNotLike($field, $condition, $logic = 'AND')
  1028. {
  1029. $this->parseWhereExp($logic, $field, 'not like', $condition);
  1030. return $this;
  1031. }
  1032. /**
  1033. * 指定Between查询条件
  1034. * @access public
  1035. * @param mixed $field 查询字段
  1036. * @param mixed $condition 查询条件
  1037. * @param string $logic 查询逻辑 and or xor
  1038. * @return $this
  1039. */
  1040. public function whereBetween($field, $condition, $logic = 'AND')
  1041. {
  1042. $this->parseWhereExp($logic, $field, 'between', $condition);
  1043. return $this;
  1044. }
  1045. /**
  1046. * 指定NotBetween查询条件
  1047. * @access public
  1048. * @param mixed $field 查询字段
  1049. * @param mixed $condition 查询条件
  1050. * @param string $logic 查询逻辑 and or xor
  1051. * @return $this
  1052. */
  1053. public function whereNotBetween($field, $condition, $logic = 'AND')
  1054. {
  1055. $this->parseWhereExp($logic, $field, 'not between', $condition);
  1056. return $this;
  1057. }
  1058. /**
  1059. * 指定Exp查询条件
  1060. * @access public
  1061. * @param mixed $field 查询字段
  1062. * @param mixed $condition 查询条件
  1063. * @param string $logic 查询逻辑 and or xor
  1064. * @return $this
  1065. */
  1066. public function whereExp($field, $condition, $logic = 'AND')
  1067. {
  1068. $this->parseWhereExp($logic, $field, 'exp', $condition);
  1069. return $this;
  1070. }
  1071. /**
  1072. * 分析查询表达式
  1073. * @access public
  1074. * @param string $logic 查询逻辑 and or xor
  1075. * @param string|array|\Closure $field 查询字段
  1076. * @param mixed $op 查询表达式
  1077. * @param mixed $condition 查询条件
  1078. * @param array $param 查询参数
  1079. * @return void
  1080. */
  1081. protected function parseWhereExp($logic, $field, $op, $condition, $param = [])
  1082. {
  1083. $logic = strtoupper($logic);
  1084. if ($field instanceof \Closure) {
  1085. $this->options['where'][$logic][] = is_string($op) ? [$op, $field] : $field;
  1086. return;
  1087. }
  1088. if (is_string($field) && !empty($this->options['via']) && !strpos($field, '.')) {
  1089. $field = $this->options['via'] . '.' . $field;
  1090. }
  1091. if (is_string($field) && preg_match('/[,=\>\<\'\"\(\s]/', $field)) {
  1092. $where[] = ['exp', $field];
  1093. if (is_array($op)) {
  1094. // 参数绑定
  1095. $this->bind($op);
  1096. }
  1097. } elseif (is_null($op) && is_null($condition)) {
  1098. if (is_array($field)) {
  1099. // 数组批量查询
  1100. $where = $field;
  1101. foreach ($where as $k => $val) {
  1102. $this->options['multi'][$logic][$k][] = $val;
  1103. }
  1104. } elseif ($field && is_string($field)) {
  1105. // 字符串查询
  1106. $where[$field] = ['null', ''];
  1107. $this->options['multi'][$logic][$field][] = $where[$field];
  1108. }
  1109. } elseif (is_array($op)) {
  1110. $where[$field] = $param;
  1111. } elseif (in_array(strtolower($op), ['null', 'notnull', 'not null'])) {
  1112. // null查询
  1113. $where[$field] = [$op, ''];
  1114. $this->options['multi'][$logic][$field][] = $where[$field];
  1115. } elseif (is_null($condition)) {
  1116. // 字段相等查询
  1117. $where[$field] = ['eq', $op];
  1118. if ('AND' != $logic) {
  1119. $this->options['multi'][$logic][$field][] = $where[$field];
  1120. }
  1121. } else {
  1122. $where[$field] = [$op, $condition, isset($param[2]) ? $param[2] : null];
  1123. if ('exp' == strtolower($op) && isset($param[2]) && is_array($param[2])) {
  1124. // 参数绑定
  1125. $this->bind($param[2]);
  1126. }
  1127. // 记录一个字段多次查询条件
  1128. $this->options['multi'][$logic][$field][] = $where[$field];
  1129. }
  1130. if (!empty($where)) {
  1131. if (!isset($this->options['where'][$logic])) {
  1132. $this->options['where'][$logic] = [];
  1133. }
  1134. if (is_string($field) && $this->checkMultiField($field, $logic)) {
  1135. $where[$field] = $this->options['multi'][$logic][$field];
  1136. } elseif (is_array($field)) {
  1137. foreach ($field as $key => $val) {
  1138. if ($this->checkMultiField($key, $logic)) {
  1139. $where[$key] = $this->options['multi'][$logic][$key];
  1140. }
  1141. }
  1142. }
  1143. $this->options['where'][$logic] = array_merge($this->options['where'][$logic], $where);
  1144. }
  1145. }
  1146. /**
  1147. * 检查是否存在一个字段多次查询条件
  1148. * @access public
  1149. * @param string $field 查询字段
  1150. * @param string $logic 查询逻辑 and or xor
  1151. * @return bool
  1152. */
  1153. private function checkMultiField($field, $logic)
  1154. {
  1155. return isset($this->options['multi'][$logic][$field]) && count($this->options['multi'][$logic][$field]) > 1;
  1156. }
  1157. /**
  1158. * 去除某个查询条件
  1159. * @access public
  1160. * @param string $field 查询字段
  1161. * @param string $logic 查询逻辑 and or xor
  1162. * @return $this
  1163. */
  1164. public function removeWhereField($field, $logic = 'AND')
  1165. {
  1166. $logic = strtoupper($logic);
  1167. if (isset($this->options['where'][$logic][$field])) {
  1168. unset($this->options['where'][$logic][$field]);
  1169. }
  1170. return $this;
  1171. }
  1172. /**
  1173. * 去除查询参数
  1174. * @access public
  1175. * @param string|bool $option 参数名 true 表示去除所有参数
  1176. * @return $this
  1177. */
  1178. public function removeOption($option = true)
  1179. {
  1180. if (true === $option) {
  1181. $this->options = [];
  1182. } elseif (is_string($option) && isset($this->options[$option])) {
  1183. unset($this->options[$option]);
  1184. }
  1185. return $this;
  1186. }
  1187. /**
  1188. * 指定查询数量
  1189. * @access public
  1190. * @param mixed $offset 起始位置
  1191. * @param mixed $length 查询数量
  1192. * @return $this
  1193. */
  1194. public function limit($offset, $length = null)
  1195. {
  1196. if (is_null($length) && strpos($offset, ',')) {
  1197. list($offset, $length) = explode(',', $offset);
  1198. }
  1199. $this->options['limit'] = intval($offset) . ($length ? ',' . intval($length) : '');
  1200. return $this;
  1201. }
  1202. /**
  1203. * 指定分页
  1204. * @access public
  1205. * @param mixed $page 页数
  1206. * @param mixed $listRows 每页数量
  1207. * @return $this
  1208. */
  1209. public function page($page, $listRows = null)
  1210. {
  1211. if (is_null($listRows) && strpos($page, ',')) {
  1212. list($page, $listRows) = explode(',', $page);
  1213. }
  1214. $this->options['page'] = [intval($page), intval($listRows)];
  1215. return $this;
  1216. }
  1217. /**
  1218. * 分页查询
  1219. * @param int|array $listRows 每页数量 数组表示配置参数
  1220. * @param int|bool $simple 是否简洁模式或者总记录数
  1221. * @param array $config 配置参数
  1222. * page:当前页,
  1223. * path:url路径,
  1224. * query:url额外参数,
  1225. * fragment:url锚点,
  1226. * var_page:分页变量,
  1227. * list_rows:每页数量
  1228. * type:分页类名
  1229. * @return \think\Paginator
  1230. * @throws DbException
  1231. */
  1232. public function paginate($listRows = null, $simple = false, $config = [])
  1233. {
  1234. if (is_int($simple)) {
  1235. $total = $simple;
  1236. $simple = false;
  1237. }
  1238. if (is_array($listRows)) {
  1239. $config = array_merge(Config::get('paginate'), $listRows);
  1240. $listRows = $config['list_rows'];
  1241. } else {
  1242. $config = array_merge(Config::get('paginate'), $config);
  1243. $listRows = $listRows ?: $config['list_rows'];
  1244. }
  1245. /** @var Paginator $class */
  1246. $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\paginator\\driver\\' . ucwords($config['type']);
  1247. $page = isset($config['page']) ? (int) $config['page'] : call_user_func([
  1248. $class,
  1249. 'getCurrentPage',
  1250. ], $config['var_page']);
  1251. $page = $page < 1 ? 1 : $page;
  1252. $config['path'] = isset($config['path']) ? $config['path'] : call_user_func([$class, 'getCurrentPath']);
  1253. if (!isset($total) && !$simple) {
  1254. $options = $this->getOptions();
  1255. unset($this->options['order'], $this->options['limit'], $this->options['page'], $this->options['field']);
  1256. $bind = $this->bind;
  1257. $total = $this->count();
  1258. $results = $this->options($options)->bind($bind)->page($page, $listRows)->select();
  1259. } elseif ($simple) {
  1260. $results = $this->limit(($page - 1) * $listRows, $listRows + 1)->select();
  1261. $total = null;
  1262. } else {
  1263. $results = $this->page($page, $listRows)->select();
  1264. }
  1265. return $class::make($results, $listRows, $page, $total, $simple, $config);
  1266. }
  1267. /**
  1268. * 指定当前操作的数据表
  1269. * @access public
  1270. * @param mixed $table 表名
  1271. * @return $this
  1272. */
  1273. public function table($table)
  1274. {
  1275. if (is_string($table)) {
  1276. if (strpos($table, ')')) {
  1277. // 子查询
  1278. } elseif (strpos($table, ',')) {
  1279. $tables = explode(',', $table);
  1280. $table = [];
  1281. foreach ($tables as $item) {
  1282. list($item, $alias) = explode(' ', trim($item));
  1283. if ($alias) {
  1284. $this->alias([$item => $alias]);
  1285. $table[$item] = $alias;
  1286. } else {
  1287. $table[] = $item;
  1288. }
  1289. }
  1290. } elseif (strpos($table, ' ')) {
  1291. list($table, $alias) = explode(' ', $table);
  1292. $table = [$table => $alias];
  1293. $this->alias($table);
  1294. }
  1295. } else {
  1296. $tables = $table;
  1297. $table = [];
  1298. foreach ($tables as $key => $val) {
  1299. if (is_numeric($key)) {
  1300. $table[] = $val;
  1301. } else {
  1302. $this->alias([$key => $val]);
  1303. $table[$key] = $val;
  1304. }
  1305. }
  1306. }
  1307. $this->options['table'] = $table;
  1308. return $this;
  1309. }
  1310. /**
  1311. * USING支持 用于多表删除
  1312. * @access public
  1313. * @param mixed $using
  1314. * @return $this
  1315. */
  1316. public function using($using)
  1317. {
  1318. $this->options['using'] = $using;
  1319. return $this;
  1320. }
  1321. /**
  1322. * 指定排序 order('id','desc') 或者 order(['id'=>'desc','create_time'=>'desc'])
  1323. * @access public
  1324. * @param string|array $field 排序字段
  1325. * @param string $order 排序
  1326. * @return $this
  1327. */
  1328. public function order($field, $order = null)
  1329. {
  1330. if (!empty($field)) {
  1331. if (is_string($field)) {
  1332. if (!empty($this->options['via'])) {
  1333. $field = $this->options['via'] . '.' . $field;
  1334. }
  1335. $field = empty($order) ? $field : [$field => $order];
  1336. } elseif (!empty($this->options['via'])) {
  1337. foreach ($field as $key => $val) {
  1338. if (is_numeric($key)) {
  1339. $field[$key] = $this->options['via'] . '.' . $val;
  1340. } else {
  1341. $field[$this->options['via'] . '.' . $key] = $val;
  1342. unset($field[$key]);
  1343. }
  1344. }
  1345. }
  1346. if (!isset($this->options['order'])) {
  1347. $this->options['order'] = [];
  1348. }
  1349. if (is_array($field)) {
  1350. $this->options['order'] = array_merge($this->options['order'], $field);
  1351. } else {
  1352. $this->options['order'][] = $field;
  1353. }
  1354. }
  1355. return $this;
  1356. }
  1357. /**
  1358. * 查询缓存
  1359. * @access public
  1360. * @param mixed $key 缓存key
  1361. * @param integer $expire 缓存有效期
  1362. * @param string $tag 缓存标签
  1363. * @return $this
  1364. */
  1365. public function cache($key = true, $expire = null, $tag = null)
  1366. {
  1367. // 增加快捷调用方式 cache(10) 等同于 cache(true, 10)
  1368. if (is_numeric($key) && is_null($expire)) {
  1369. $expire = $key;
  1370. $key = true;
  1371. }
  1372. if (false !== $key) {
  1373. $this->options['cache'] = ['key' => $key, 'expire' => $expire, 'tag' => $tag];
  1374. }
  1375. return $this;
  1376. }
  1377. /**
  1378. * 指定group查询
  1379. * @access public
  1380. * @param string $group GROUP
  1381. * @return $this
  1382. */
  1383. public function group($group)
  1384. {
  1385. $this->options['group'] = $group;
  1386. return $this;
  1387. }
  1388. /**
  1389. * 指定having查询
  1390. * @access public
  1391. * @param string $having having
  1392. * @return $this
  1393. */
  1394. public function having($having)
  1395. {
  1396. $this->options['having'] = $having;
  1397. return $this;
  1398. }
  1399. /**
  1400. * 指定查询lock
  1401. * @access public
  1402. * @param boolean $lock 是否lock
  1403. * @return $this
  1404. */
  1405. public function lock($lock = false)
  1406. {
  1407. $this->options['lock'] = $lock;
  1408. $this->options['master'] = true;
  1409. return $this;
  1410. }
  1411. /**
  1412. * 指定distinct查询
  1413. * @access public
  1414. * @param string $distinct 是否唯一
  1415. * @return $this
  1416. */
  1417. public function distinct($distinct)
  1418. {
  1419. $this->options['distinct'] = $distinct;
  1420. return $this;
  1421. }
  1422. /**
  1423. * 指定数据表别名
  1424. * @access public
  1425. * @param mixed $alias 数据表别名
  1426. * @return $this
  1427. */
  1428. public function alias($alias)
  1429. {
  1430. if (is_array($alias)) {
  1431. foreach ($alias as $key => $val) {
  1432. $this->options['alias'][$key] = $val;
  1433. }
  1434. } else {
  1435. if (isset($this->options['table'])) {
  1436. $table = is_array($this->options['table']) ? key($this->options['table']) : $this->options['table'];
  1437. if (false !== strpos($table, '__')) {
  1438. $table = $this->parseSqlTable($table);
  1439. }
  1440. } else {
  1441. $table = $this->getTable();
  1442. }
  1443. $this->options['alias'][$table] = $alias;
  1444. }
  1445. return $this;
  1446. }
  1447. /**
  1448. * 指定强制索引
  1449. * @access public
  1450. * @param string $force 索引名称
  1451. * @return $this
  1452. */
  1453. public function force($force)
  1454. {
  1455. $this->options['force'] = $force;
  1456. return $this;
  1457. }
  1458. /**
  1459. * 查询注释
  1460. * @access public
  1461. * @param string $comment 注释
  1462. * @return $this
  1463. */
  1464. public function comment($comment)
  1465. {
  1466. $this->options['comment'] = $comment;
  1467. return $this;
  1468. }
  1469. /**
  1470. * 获取执行的SQL语句
  1471. * @access public
  1472. * @param boolean $fetch 是否返回sql
  1473. * @return $this
  1474. */
  1475. public function fetchSql($fetch = true)
  1476. {
  1477. $this->options['fetch_sql'] = $fetch;
  1478. return $this;
  1479. }
  1480. /**
  1481. * 不主动获取数据集
  1482. * @access public
  1483. * @param bool $pdo 是否返回 PDOStatement 对象
  1484. * @return $this
  1485. */
  1486. public function fetchPdo($pdo = true)
  1487. {
  1488. $this->options['fetch_pdo'] = $pdo;
  1489. return $this;
  1490. }
  1491. /**
  1492. * 设置从主服务器读取数据
  1493. * @access public
  1494. * @return $this
  1495. */
  1496. public function master()
  1497. {
  1498. $this->options['master'] = true;
  1499. return $this;
  1500. }
  1501. /**
  1502. * 设置是否严格检查字段名
  1503. * @access public
  1504. * @param bool $strict 是否严格检查字段
  1505. * @return $this
  1506. */
  1507. public function strict($strict = true)
  1508. {
  1509. $this->options['strict'] = $strict;
  1510. return $this;
  1511. }
  1512. /**
  1513. * 设置查询数据不存在是否抛出异常
  1514. * @access public
  1515. * @param bool $fail 数据不存在是否抛出异常
  1516. * @return $this
  1517. */
  1518. public function failException($fail = true)
  1519. {
  1520. $this->options['fail'] = $fail;
  1521. return $this;
  1522. }
  1523. /**
  1524. * 设置自增序列名
  1525. * @access public
  1526. * @param string $sequence 自增序列名
  1527. * @return $this
  1528. */
  1529. public function sequence($sequence = null)
  1530. {
  1531. $this->options['sequence'] = $sequence;
  1532. return $this;
  1533. }
  1534. /**
  1535. * 指定数据表主键
  1536. * @access public
  1537. * @param string $pk 主键
  1538. * @return $this
  1539. */
  1540. public function pk($pk)
  1541. {
  1542. $this->pk = $pk;
  1543. return $this;
  1544. }
  1545. /**
  1546. * 查询日期或者时间
  1547. * @access public
  1548. * @param string $field 日期字段名
  1549. * @param string $op 比较运算符或者表达式
  1550. * @param string|array $range 比较范围
  1551. * @return $this
  1552. */
  1553. public function whereTime($field, $op, $range = null)
  1554. {
  1555. if (is_null($range)) {
  1556. // 使用日期表达式
  1557. $date = getdate();
  1558. switch (strtolower($op)) {
  1559. case 'today':
  1560. case 'd':
  1561. $range = ['today', 'tomorrow'];
  1562. break;
  1563. case 'week':
  1564. case 'w':
  1565. $range = 'this week 00:00:00';
  1566. break;
  1567. case 'month':
  1568. case 'm':
  1569. $range = mktime(0, 0, 0, $date['mon'], 1, $date['year']);
  1570. break;
  1571. case 'year':
  1572. case 'y':
  1573. $range = mktime(0, 0, 0, 1, 1, $date['year']);
  1574. break;
  1575. case 'yesterday':
  1576. $range = ['yesterday', 'today'];
  1577. break;
  1578. case 'last week':
  1579. $range = ['last week 00:00:00', 'this week 00:00:00'];
  1580. break;
  1581. case 'last month':
  1582. $range = [date('y-m-01', strtotime('-1 month')), mktime(0, 0, 0, $date['mon'], 1, $date['year'])];
  1583. break;
  1584. case 'last year':
  1585. $range = [mktime(0, 0, 0, 1, 1, $date['year'] - 1), mktime(0, 0, 0, 1, 1, $date['year'])];
  1586. break;
  1587. default:
  1588. $range = $op;
  1589. }
  1590. $op = is_array($range) ? 'between' : '>';
  1591. }
  1592. $this->where($field, strtolower($op) . ' time', $range);
  1593. return $this;
  1594. }
  1595. /**
  1596. * 获取数据表信息
  1597. * @access public
  1598. * @param mixed $tableName 数据表名 留空自动获取
  1599. * @param string $fetch 获取信息类型 包括 fields type bind pk
  1600. * @return mixed
  1601. */
  1602. public function getTableInfo($tableName = '', $fetch = '')
  1603. {
  1604. if (!$tableName) {
  1605. $tableName = $this->getTable();
  1606. }
  1607. if (is_array($tableName)) {
  1608. $tableName = key($tableName) ?: current($tableName);
  1609. }
  1610. if (strpos($tableName, ',')) {
  1611. // 多表不获取字段信息
  1612. return false;
  1613. } else {
  1614. $tableName = $this->parseSqlTable($tableName);
  1615. }
  1616. // 修正子查询作为表名的问题
  1617. if (strpos($tableName, ')')) {
  1618. return [];
  1619. }
  1620. list($guid) = explode(' ', $tableName);
  1621. $db = $this->getConfig('database');
  1622. if (!isset(self::$info[$db . '.' . $guid])) {
  1623. if (!strpos($guid, '.')) {
  1624. $schema = $db . '.' . $guid;
  1625. } else {
  1626. $schema = $guid;
  1627. }
  1628. // 读取缓存
  1629. if (is_file(RUNTIME_PATH . 'schema/' . $schema . '.php')) {
  1630. $info = include RUNTIME_PATH . 'schema/' . $schema . '.php';
  1631. } else {
  1632. $info = $this->connection->getFields($guid);
  1633. }
  1634. $fields = array_keys($info);
  1635. $bind = $type = [];
  1636. foreach ($info as $key => $val) {
  1637. // 记录字段类型
  1638. $type[$key] = $val['type'];
  1639. $bind[$key] = $this->getFieldBindType($val['type']);
  1640. if (!empty($val['primary'])) {
  1641. $pk[] = $key;
  1642. }
  1643. }
  1644. if (isset($pk)) {
  1645. // 设置主键
  1646. $pk = count($pk) > 1 ? $pk : $pk[0];
  1647. } else {
  1648. $pk = null;
  1649. }
  1650. self::$info[$db . '.' . $guid] = ['fields' => $fields, 'type' => $type, 'bind' => $bind, 'pk' => $pk];
  1651. }
  1652. return $fetch ? self::$info[$db . '.' . $guid][$fetch] : self::$info[$db . '.' . $guid];
  1653. }
  1654. /**
  1655. * 获取当前数据表的主键
  1656. * @access public
  1657. * @param string|array $options 数据表名或者查询参数
  1658. * @return string|array
  1659. */
  1660. public function getPk($options = '')
  1661. {
  1662. if (!empty($this->pk)) {
  1663. $pk = $this->pk;
  1664. } else {
  1665. $pk = $this->getTableInfo(is_array($options) ? $options['table'] : $options, 'pk');
  1666. }
  1667. return $pk;
  1668. }
  1669. // 获取当前数据表字段信息
  1670. public function getTableFields($options)
  1671. {
  1672. return $this->getTableInfo($options['table'], 'fields');
  1673. }
  1674. // 获取当前数据表字段类型
  1675. public function getFieldsType($options)
  1676. {
  1677. return $this->getTableInfo($options['table'], 'type');
  1678. }
  1679. // 获取当前数据表绑定信息
  1680. public function getFieldsBind($options)
  1681. {
  1682. $types = $this->getFieldsType($options);
  1683. $bind = [];
  1684. if ($types) {
  1685. foreach ($types as $key => $type) {
  1686. $bind[$key] = $this->getFieldBindType($type);
  1687. }
  1688. }
  1689. return $bind;
  1690. }
  1691. /**
  1692. * 获取字段绑定类型
  1693. * @access public
  1694. * @param string $type 字段类型
  1695. * @return integer
  1696. */
  1697. protected function getFieldBindType($type)
  1698. {
  1699. if (preg_match('/(int|double|float|decimal|real|numeric|serial|bit)/is', $type)) {
  1700. $bind = PDO::PARAM_INT;
  1701. } elseif (preg_match('/bool/is', $type)) {
  1702. $bind = PDO::PARAM_BOOL;
  1703. } else {
  1704. $bind = PDO::PARAM_STR;
  1705. }
  1706. return $bind;
  1707. }
  1708. /**
  1709. * 参数绑定
  1710. * @access public
  1711. * @param mixed $key 参数名
  1712. * @param mixed $value 绑定变量值
  1713. * @param integer $type 绑定类型
  1714. * @return $this
  1715. */
  1716. public function bind($key, $value = false, $type = PDO::PARAM_STR)
  1717. {
  1718. if (is_array($key)) {
  1719. $this->bind = array_merge($this->bind, $key);
  1720. } else {
  1721. $this->bind[$key] = [$value, $type];
  1722. }
  1723. return $this;
  1724. }
  1725. /**
  1726. * 检测参数是否已经绑定
  1727. * @access public
  1728. * @param string $key 参数名
  1729. * @return bool
  1730. */
  1731. public function isBind($key)
  1732. {
  1733. return isset($this->bind[$key]);
  1734. }
  1735. /**
  1736. * 查询参数赋值
  1737. * @access protected
  1738. * @param array $options 表达式参数
  1739. * @return $this
  1740. */
  1741. protected function options(array $options)
  1742. {
  1743. $this->options = $options;
  1744. return $this;
  1745. }
  1746. /**
  1747. * 获取当前的查询参数
  1748. * @access public
  1749. * @param string $name 参数名
  1750. * @return mixed
  1751. */
  1752. public function getOptions($name = '')
  1753. {
  1754. if ('' === $name) {
  1755. return $this->options;
  1756. } else {
  1757. return isset($this->options[$name]) ? $this->options[$name] : null;
  1758. }
  1759. }
  1760. /**
  1761. * 设置关联查询JOIN预查询
  1762. * @access public
  1763. * @param string|array $with 关联方法名称
  1764. * @return $this
  1765. */
  1766. public function with($with)
  1767. {
  1768. if (empty($with)) {
  1769. return $this;
  1770. }
  1771. if (is_string($with)) {
  1772. $with = explode(',', $with);
  1773. }
  1774. $first = true;
  1775. $currentModel = $this->model;
  1776. /** @var Model $class */
  1777. $class = new $currentModel;
  1778. foreach ($with as $key => $relation) {
  1779. $subRelation = '';
  1780. $closure = false;
  1781. if ($relation instanceof \Closure) {
  1782. // 支持闭包查询过滤关联条件
  1783. $closure = $relation;
  1784. $relation = $key;
  1785. $with[$key] = $key;
  1786. } elseif (is_string($relation) && strpos($relation, '.')) {
  1787. $with[$key] = $relation;
  1788. list($relation, $subRelation) = explode('.', $relation, 2);
  1789. }
  1790. /** @var Relation $model */
  1791. $relation = Loader::parseName($relation, 1, false);
  1792. $model = $class->$relation();
  1793. if ($model instanceof OneToOne && 0 == $model->getEagerlyType()) {
  1794. $model->eagerly($this, $relation, $subRelation, $closure, $first);
  1795. $first = false;
  1796. } elseif ($closure) {
  1797. $with[$key] = $closure;
  1798. }
  1799. }
  1800. $this->via();
  1801. if (isset($this->options['with'])) {
  1802. $this->options['with'] = array_merge($this->options['with'], $with);
  1803. } else {
  1804. $this->options['with'] = $with;
  1805. }
  1806. return $this;
  1807. }
  1808. /**
  1809. * 关联统计
  1810. * @access public
  1811. * @param string|array $relation 关联方法名
  1812. * @param bool $subQuery 是否使用子查询
  1813. * @return $this
  1814. */
  1815. public function withCount($relation, $subQuery = true)
  1816. {
  1817. if (!$subQuery) {
  1818. $this->options['with_count'] = $relation;
  1819. } else {
  1820. $relations = is_string($relation) ? explode(',', $relation) : $relation;
  1821. if (!isset($this->options['field'])) {
  1822. $this->field('*');
  1823. }
  1824. foreach ($relations as $key => $relation) {
  1825. $closure = false;
  1826. if ($relation instanceof \Closure) {
  1827. $closure = $relation;
  1828. $relation = $key;
  1829. }
  1830. $relation = Loader::parseName($relation, 1, false);
  1831. $count = '(' . (new $this->model)->$relation()->getRelationCountQuery($closure) . ')';
  1832. $this->field([$count => Loader::parseName($relation) . '_count']);
  1833. }
  1834. }
  1835. return $this;
  1836. }
  1837. /**
  1838. * 关联预加载中 获取关联指定字段值
  1839. * example:
  1840. * Model::with(['relation' => function($query){
  1841. * $query->withField("id,name");
  1842. * }])
  1843. *
  1844. * @param string | array $field 指定获取的字段
  1845. * @return $this
  1846. */
  1847. public function withField($field)
  1848. {
  1849. $this->options['with_field'] = $field;
  1850. return $this;
  1851. }
  1852. /**
  1853. * 设置当前字段添加的表别名
  1854. * @access public
  1855. * @param string $via
  1856. * @return $this
  1857. */
  1858. public function via($via = '')
  1859. {
  1860. $this->options['via'] = $via;
  1861. return $this;
  1862. }
  1863. /**
  1864. * 设置关联查询
  1865. * @access public
  1866. * @param string|array $relation 关联名称
  1867. * @return $this
  1868. */
  1869. public function relation($relation)
  1870. {
  1871. if (empty($relation)) {
  1872. return $this;
  1873. }
  1874. if (is_string($relation)) {
  1875. $relation = explode(',', $relation);
  1876. }
  1877. if (isset($this->options['relation'])) {
  1878. $this->options['relation'] = array_mrege($this->options['relation'], $relation);
  1879. } else {
  1880. $this->options['relation'] = $relation;
  1881. }
  1882. return $this;
  1883. }
  1884. /**
  1885. * 把主键值转换为查询条件 支持复合主键
  1886. * @access public
  1887. * @param array|string $data 主键数据
  1888. * @param mixed $options 表达式参数
  1889. * @return void
  1890. * @throws Exception
  1891. */
  1892. protected function parsePkWhere($data, &$options)
  1893. {
  1894. $pk = $this->getPk($options);
  1895. // 获取当前数据表
  1896. $table = is_array($options['table']) ? key($options['table']) : $options['table'];
  1897. if (!empty($options['alias'][$table])) {
  1898. $alias = $options['alias'][$table];
  1899. }
  1900. if (is_string($pk)) {
  1901. $key = isset($alias) ? $alias . '.' . $pk : $pk;
  1902. // 根据主键查询
  1903. if (is_array($data)) {
  1904. $where[$key] = isset($data[$pk]) ? $data[$pk] : ['in', $data];
  1905. } else {
  1906. $where[$key] = strpos($data, ',') ? ['IN', $data] : $data;
  1907. }
  1908. } elseif (is_array($pk) && is_array($data) && !empty($data)) {
  1909. // 根据复合主键查询
  1910. foreach ($pk as $key) {
  1911. if (isset($data[$key])) {
  1912. $attr = isset($alias) ? $alias . '.' . $key : $key;
  1913. $where[$attr] = $data[$key];
  1914. } else {
  1915. throw new Exception('miss complex primary data');
  1916. }
  1917. }
  1918. }
  1919. if (!empty($where)) {
  1920. if (isset($options['where']['AND'])) {
  1921. $options['where']['AND'] = array_merge($options['where']['AND'], $where);
  1922. } else {
  1923. $options['where']['AND'] = $where;
  1924. }
  1925. }
  1926. return;
  1927. }
  1928. /**
  1929. * 插入记录
  1930. * @access public
  1931. * @param mixed $data 数据
  1932. * @param boolean $replace 是否replace
  1933. * @param boolean $getLastInsID 返回自增主键
  1934. * @param string $sequence 自增序列名
  1935. * @return integer|string
  1936. */
  1937. public function insert(array $data = [], $replace = false, $getLastInsID = false, $sequence = null)
  1938. {
  1939. // 分析查询表达式
  1940. $options = $this->parseExpress();
  1941. $data = array_merge($options['data'], $data);
  1942. // 生成SQL语句
  1943. $sql = $this->builder->insert($data, $options, $replace);
  1944. // 获取参数绑定
  1945. $bind = $this->getBind();
  1946. if ($options['fetch_sql']) {
  1947. // 获取实际执行的SQL语句
  1948. return $this->connection->getRealSql($sql, $bind);
  1949. }
  1950. // 执行操作
  1951. $result = $this->execute($sql, $bind);
  1952. if ($result) {
  1953. $this->trigger('after_insert', $options);
  1954. }
  1955. if ($getLastInsID) {
  1956. $sequence = $sequence ?: (isset($options['sequence']) ? $options['sequence'] : null);
  1957. return $this->getLastInsID($sequence);
  1958. }
  1959. return $result;
  1960. }
  1961. /**
  1962. * 插入记录并获取自增ID
  1963. * @access public
  1964. * @param mixed $data 数据
  1965. * @param boolean $replace 是否replace
  1966. * @param string $sequence 自增序列名
  1967. * @return integer|string
  1968. */
  1969. public function insertGetId(array $data, $replace = false, $sequence = null)
  1970. {
  1971. return $this->insert($data, $replace, true, $sequence);
  1972. }
  1973. /**
  1974. * 批量插入记录
  1975. * @access public
  1976. * @param mixed $dataSet 数据集
  1977. * @return integer|string
  1978. */
  1979. public function insertAll(array $dataSet)
  1980. {
  1981. // 分析查询表达式
  1982. $options = $this->parseExpress();
  1983. if (!is_array(reset($dataSet))) {
  1984. return false;
  1985. }
  1986. // 生成SQL语句
  1987. $sql = $this->builder->insertAll($dataSet, $options);
  1988. // 获取参数绑定
  1989. $bind = $this->getBind();
  1990. if ($options['fetch_sql']) {
  1991. // 获取实际执行的SQL语句
  1992. return $this->connection->getRealSql($sql, $bind);
  1993. } else {
  1994. // 执行操作
  1995. return $this->execute($sql, $bind);
  1996. }
  1997. }
  1998. /**
  1999. * 通过Select方式插入记录
  2000. * @access public
  2001. * @param string $fields 要插入的数据表字段名
  2002. * @param string $table 要插入的数据表名
  2003. * @return integer|string
  2004. * @throws PDOException
  2005. */
  2006. public function selectInsert($fields, $table)
  2007. {
  2008. // 分析查询表达式
  2009. $options = $this->parseExpress();
  2010. // 生成SQL语句
  2011. $table = $this->parseSqlTable($table);
  2012. $sql = $this->builder->selectInsert($fields, $table, $options);
  2013. // 获取参数绑定
  2014. $bind = $this->getBind();
  2015. if ($options['fetch_sql']) {
  2016. // 获取实际执行的SQL语句
  2017. return $this->connection->getRealSql($sql, $bind);
  2018. } else {
  2019. // 执行操作
  2020. return $this->execute($sql, $bind);
  2021. }
  2022. }
  2023. /**
  2024. * 更新记录
  2025. * @access public
  2026. * @param mixed $data 数据
  2027. * @return integer|string
  2028. * @throws Exception
  2029. * @throws PDOException
  2030. */
  2031. public function update(array $data = [])
  2032. {
  2033. $options = $this->parseExpress();
  2034. $data = array_merge($options['data'], $data);
  2035. $pk = $this->getPk($options);
  2036. if (isset($options['cache']) && is_string($options['cache'])) {
  2037. $key = $options['cache'];
  2038. }
  2039. if (empty($options['where'])) {
  2040. // 如果存在主键数据 则自动作为更新条件
  2041. if (is_string($pk) && isset($data[$pk])) {
  2042. $where[$pk] = $data[$pk];
  2043. if (!isset($key)) {
  2044. $key = 'think:' . $options['table'] . '|' . $data[$pk];
  2045. }
  2046. unset($data[$pk]);
  2047. } elseif (is_array($pk)) {
  2048. // 增加复合主键支持
  2049. foreach ($pk as $field) {
  2050. if (isset($data[$field])) {
  2051. $where[$field] = $data[$field];
  2052. } else {
  2053. // 如果缺少复合主键数据则不执行
  2054. throw new Exception('miss complex primary data');
  2055. }
  2056. unset($data[$field]);
  2057. }
  2058. }
  2059. if (!isset($where)) {
  2060. // 如果没有任何更新条件则不执行
  2061. throw new Exception('miss update condition');
  2062. } else {
  2063. $options['where']['AND'] = $where;
  2064. }
  2065. } elseif (is_string($pk) && isset($options['where']['AND'][$pk]) && is_scalar($options['where']['AND'][$pk])) {
  2066. $key = 'think:' . $options['table'] . '|' . $options['where']['AND'][$pk];
  2067. }
  2068. // 生成UPDATE SQL语句
  2069. $sql = $this->builder->update($data, $options);
  2070. // 获取参数绑定
  2071. $bind = $this->getBind();
  2072. if ($options['fetch_sql']) {
  2073. // 获取实际执行的SQL语句
  2074. return $this->connection->getRealSql($sql, $bind);
  2075. } else {
  2076. // 检测缓存
  2077. if (isset($key) && Cache::get($key)) {
  2078. // 删除缓存
  2079. Cache::rm($key);
  2080. }
  2081. // 执行操作
  2082. $result = '' == $sql ? 0 : $this->execute($sql, $bind);
  2083. if ($result) {
  2084. $this->trigger('after_update', $options);
  2085. }
  2086. return $result;
  2087. }
  2088. }
  2089. /**
  2090. * 执行查询但只返回PDOStatement对象
  2091. * @access public
  2092. * @return \PDOStatement|string
  2093. */
  2094. public function getPdo()
  2095. {
  2096. // 分析查询表达式
  2097. $options = $this->parseExpress();
  2098. // 生成查询SQL
  2099. $sql = $this->builder->select($options);
  2100. // 获取参数绑定
  2101. $bind = $this->getBind();
  2102. if ($options['fetch_sql']) {
  2103. // 获取实际执行的SQL语句
  2104. return $this->connection->getRealSql($sql, $bind);
  2105. }
  2106. // 执行查询操作
  2107. return $this->query($sql, $bind, $options['master'], true);
  2108. }
  2109. /**
  2110. * 查找记录
  2111. * @access public
  2112. * @param array|string|Query|\Closure $data
  2113. * @return Collection|false|\PDOStatement|string
  2114. * @throws DbException
  2115. * @throws ModelNotFoundException
  2116. * @throws DataNotFoundException
  2117. */
  2118. public function select($data = null)
  2119. {
  2120. if ($data instanceof Query) {
  2121. return $data->select();
  2122. } elseif ($data instanceof \Closure) {
  2123. call_user_func_array($data, [ & $this]);
  2124. $data = null;
  2125. }
  2126. // 分析查询表达式
  2127. $options = $this->parseExpress();
  2128. if (false === $data) {
  2129. // 用于子查询 不查询只返回SQL
  2130. $options['fetch_sql'] = true;
  2131. } elseif (!is_null($data)) {
  2132. // 主键条件分析
  2133. $this->parsePkWhere($data, $options);
  2134. }
  2135. $resultSet = false;
  2136. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  2137. // 判断查询缓存
  2138. $cache = $options['cache'];
  2139. unset($options['cache']);
  2140. $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options));
  2141. $resultSet = Cache::get($key);
  2142. }
  2143. if (!$resultSet) {
  2144. // 生成查询SQL
  2145. $sql = $this->builder->select($options);
  2146. // 获取参数绑定
  2147. $bind = $this->getBind();
  2148. if ($options['fetch_sql']) {
  2149. // 获取实际执行的SQL语句
  2150. return $this->connection->getRealSql($sql, $bind);
  2151. }
  2152. if ($resultSet = $this->trigger('before_select', $options)) {
  2153. } else {
  2154. // 执行查询操作
  2155. $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']);
  2156. if ($resultSet instanceof \PDOStatement) {
  2157. // 返回PDOStatement对象
  2158. return $resultSet;
  2159. }
  2160. }
  2161. if (isset($cache)) {
  2162. // 缓存数据集
  2163. if (isset($cache['tag'])) {
  2164. Cache::tag($cache['tag'])->set($key, $resultSet, $cache['expire']);
  2165. } else {
  2166. Cache::set($key, $resultSet, $cache['expire']);
  2167. }
  2168. }
  2169. }
  2170. // 数据列表读取后的处理
  2171. if (!empty($this->model)) {
  2172. // 生成模型对象
  2173. $modelName = $this->model;
  2174. if (count($resultSet) > 0) {
  2175. foreach ($resultSet as $key => $result) {
  2176. /** @var Model $result */
  2177. $model = new $modelName($result);
  2178. $model->isUpdate(true);
  2179. // 关联查询
  2180. if (!empty($options['relation'])) {
  2181. $model->relationQuery($options['relation']);
  2182. }
  2183. // 关联统计
  2184. if (!empty($options['with_count'])) {
  2185. $model->relationCount($model, $options['with_count']);
  2186. }
  2187. $resultSet[$key] = $model;
  2188. }
  2189. if (!empty($options['with'])) {
  2190. // 预载入
  2191. $model->eagerlyResultSet($resultSet, $options['with']);
  2192. }
  2193. // 模型数据集转换
  2194. $resultSet = $model->toCollection($resultSet);
  2195. } else {
  2196. $resultSet = (new $modelName)->toCollection($resultSet);
  2197. }
  2198. } elseif ('collection' == $this->connection->getConfig('resultset_type')) {
  2199. // 返回Collection对象
  2200. $resultSet = new Collection($resultSet);
  2201. }
  2202. // 返回结果处理
  2203. if (!empty($options['fail']) && count($resultSet) == 0) {
  2204. $this->throwNotFound($options);
  2205. }
  2206. return $resultSet;
  2207. }
  2208. /**
  2209. * 查找单条记录
  2210. * @access public
  2211. * @param array|string|Query|\Closure $data
  2212. * @return array|false|\PDOStatement|string|Model
  2213. * @throws DbException
  2214. * @throws ModelNotFoundException
  2215. * @throws DataNotFoundException
  2216. */
  2217. public function find($data = null)
  2218. {
  2219. if ($data instanceof Query) {
  2220. return $data->find();
  2221. } elseif ($data instanceof \Closure) {
  2222. call_user_func_array($data, [ & $this]);
  2223. $data = null;
  2224. }
  2225. // 分析查询表达式
  2226. $options = $this->parseExpress();
  2227. if (!is_null($data)) {
  2228. // AR模式分析主键条件
  2229. $this->parsePkWhere($data, $options);
  2230. }
  2231. $options['limit'] = 1;
  2232. $result = false;
  2233. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  2234. // 判断查询缓存
  2235. $cache = $options['cache'];
  2236. if (true === $cache['key'] && !is_null($data) && !is_array($data)) {
  2237. $key = 'think:' . (is_array($options['table']) ? key($options['table']) : $options['table']) . '|' . $data;
  2238. } else {
  2239. $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options));
  2240. }
  2241. $result = Cache::get($key);
  2242. }
  2243. if (!$result) {
  2244. // 生成查询SQL
  2245. $sql = $this->builder->select($options);
  2246. // 获取参数绑定
  2247. $bind = $this->getBind();
  2248. if ($options['fetch_sql']) {
  2249. // 获取实际执行的SQL语句
  2250. return $this->connection->getRealSql($sql, $bind);
  2251. }
  2252. // 事件回调
  2253. if ($result = $this->trigger('before_find', $options)) {
  2254. } else {
  2255. // 执行查询
  2256. $result = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']);
  2257. if ($result instanceof \PDOStatement) {
  2258. // 返回PDOStatement对象
  2259. return $result;
  2260. }
  2261. }
  2262. if (isset($cache)) {
  2263. // 缓存数据
  2264. if (isset($cache['tag'])) {
  2265. Cache::tag($cache['tag'])->set($key, $result, $cache['expire']);
  2266. } else {
  2267. Cache::set($key, $result, $cache['expire']);
  2268. }
  2269. }
  2270. }
  2271. // 数据处理
  2272. if (!empty($result[0])) {
  2273. $data = $result[0];
  2274. if (!empty($this->model)) {
  2275. // 返回模型对象
  2276. $model = $this->model;
  2277. $data = new $model($data);
  2278. $data->isUpdate(true, isset($options['where']['AND']) ? $options['where']['AND'] : null);
  2279. // 关联查询
  2280. if (!empty($options['relation'])) {
  2281. $data->relationQuery($options['relation']);
  2282. }
  2283. // 预载入查询
  2284. if (!empty($options['with'])) {
  2285. $data->eagerlyResult($data, $options['with']);
  2286. }
  2287. // 关联统计
  2288. if (!empty($options['with_count'])) {
  2289. $data->relationCount($data, $options['with_count']);
  2290. }
  2291. }
  2292. } elseif (!empty($options['fail'])) {
  2293. $this->throwNotFound($options);
  2294. } else {
  2295. $data = null;
  2296. }
  2297. return $data;
  2298. }
  2299. /**
  2300. * 查询失败 抛出异常
  2301. * @access public
  2302. * @param array $options 查询参数
  2303. * @throws ModelNotFoundException
  2304. * @throws DataNotFoundException
  2305. */
  2306. protected function throwNotFound($options = [])
  2307. {
  2308. if (!empty($this->model)) {
  2309. throw new ModelNotFoundException('model data Not Found:' . $this->model, $this->model, $options);
  2310. } else {
  2311. $table = is_array($options['table']) ? key($options['table']) : $options['table'];
  2312. throw new DataNotFoundException('table data not Found:' . $table, $table, $options);
  2313. }
  2314. }
  2315. /**
  2316. * 查找多条记录 如果不存在则抛出异常
  2317. * @access public
  2318. * @param array|string|Query|\Closure $data
  2319. * @return array|\PDOStatement|string|Model
  2320. * @throws DbException
  2321. * @throws ModelNotFoundException
  2322. * @throws DataNotFoundException
  2323. */
  2324. public function selectOrFail($data = null)
  2325. {
  2326. return $this->failException(true)->select($data);
  2327. }
  2328. /**
  2329. * 查找单条记录 如果不存在则抛出异常
  2330. * @access public
  2331. * @param array|string|Query|\Closure $data
  2332. * @return array|\PDOStatement|string|Model
  2333. * @throws DbException
  2334. * @throws ModelNotFoundException
  2335. * @throws DataNotFoundException
  2336. */
  2337. public function findOrFail($data = null)
  2338. {
  2339. return $this->failException(true)->find($data);
  2340. }
  2341. /**
  2342. * 分批数据返回处理
  2343. * @access public
  2344. * @param integer $count 每次处理的数据数量
  2345. * @param callable $callback 处理回调方法
  2346. * @param string $column 分批处理的字段名
  2347. * @return boolean
  2348. */
  2349. public function chunk($count, $callback, $column = null)
  2350. {
  2351. $options = $this->getOptions();
  2352. if (isset($options['table'])) {
  2353. $table = is_array($options['table']) ? key($options['table']) : $options['table'];
  2354. } else {
  2355. $table = '';
  2356. }
  2357. $column = $column ?: $this->getPk($table);
  2358. $bind = $this->bind;
  2359. $resultSet = $this->limit($count)->order($column, 'asc')->select();
  2360. if (strpos($column, '.')) {
  2361. list($alias, $key) = explode('.', $column);
  2362. } else {
  2363. $key = $column;
  2364. }
  2365. if ($resultSet instanceof Collection) {
  2366. $resultSet = $resultSet->all();
  2367. }
  2368. while (!empty($resultSet)) {
  2369. if (false === call_user_func($callback, $resultSet)) {
  2370. return false;
  2371. }
  2372. $end = end($resultSet);
  2373. $lastId = is_array($end) ? $end[$key] : $end->$key;
  2374. $resultSet = $this->options($options)
  2375. ->limit($count)
  2376. ->bind($bind)
  2377. ->where($column, '>', $lastId)
  2378. ->order($column, 'asc')
  2379. ->select();
  2380. if ($resultSet instanceof Collection) {
  2381. $resultSet = $resultSet->all();
  2382. }
  2383. }
  2384. return true;
  2385. }
  2386. /**
  2387. * 获取绑定的参数 并清空
  2388. * @access public
  2389. * @return array
  2390. */
  2391. public function getBind()
  2392. {
  2393. $bind = $this->bind;
  2394. $this->bind = [];
  2395. return $bind;
  2396. }
  2397. /**
  2398. * 创建子查询SQL
  2399. * @access public
  2400. * @param bool $sub
  2401. * @return string
  2402. * @throws DbException
  2403. */
  2404. public function buildSql($sub = true)
  2405. {
  2406. return $sub ? '( ' . $this->select(false) . ' )' : $this->select(false);
  2407. }
  2408. /**
  2409. * 删除记录
  2410. * @access public
  2411. * @param mixed $data 表达式 true 表示强制删除
  2412. * @return int
  2413. * @throws Exception
  2414. * @throws PDOException
  2415. */
  2416. public function delete($data = null)
  2417. {
  2418. // 分析查询表达式
  2419. $options = $this->parseExpress();
  2420. if (isset($options['cache']) && is_string($options['cache'])) {
  2421. $key = $options['cache'];
  2422. }
  2423. if (!is_null($data) && true !== $data) {
  2424. if (!isset($key) && !is_array($data)) {
  2425. // 缓存标识
  2426. $key = 'think:' . $options['table'] . '|' . $data;
  2427. }
  2428. // AR模式分析主键条件
  2429. $this->parsePkWhere($data, $options);
  2430. }
  2431. if (true !== $data && empty($options['where'])) {
  2432. // 如果条件为空 不进行删除操作 除非设置 1=1
  2433. throw new Exception('delete without condition');
  2434. }
  2435. // 生成删除SQL语句
  2436. $sql = $this->builder->delete($options);
  2437. // 获取参数绑定
  2438. $bind = $this->getBind();
  2439. if ($options['fetch_sql']) {
  2440. // 获取实际执行的SQL语句
  2441. return $this->connection->getRealSql($sql, $bind);
  2442. }
  2443. // 检测缓存
  2444. if (isset($key) && Cache::get($key)) {
  2445. // 删除缓存
  2446. Cache::rm($key);
  2447. }
  2448. // 执行操作
  2449. $result = $this->execute($sql, $bind);
  2450. if ($result) {
  2451. $this->trigger('after_delete', $options);
  2452. }
  2453. return $result;
  2454. }
  2455. /**
  2456. * 分析表达式(可用于查询或者写入操作)
  2457. * @access protected
  2458. * @return array
  2459. */
  2460. protected function parseExpress()
  2461. {
  2462. $options = $this->options;
  2463. // 获取数据表
  2464. if (empty($options['table'])) {
  2465. $options['table'] = $this->getTable();
  2466. }
  2467. if (!isset($options['where'])) {
  2468. $options['where'] = [];
  2469. } elseif (isset($options['view'])) {
  2470. // 视图查询条件处理
  2471. foreach (['AND', 'OR'] as $logic) {
  2472. if (isset($options['where'][$logic])) {
  2473. foreach ($options['where'][$logic] as $key => $val) {
  2474. if (array_key_exists($key, $options['map'])) {
  2475. $options['where'][$logic][$options['map'][$key]] = $val;
  2476. unset($options['where'][$logic][$key]);
  2477. }
  2478. }
  2479. }
  2480. }
  2481. if (isset($options['order'])) {
  2482. // 视图查询排序处理
  2483. if (is_string($options['order'])) {
  2484. $options['order'] = explode(',', $options['order']);
  2485. }
  2486. foreach ($options['order'] as $key => $val) {
  2487. if (is_numeric($key)) {
  2488. if (strpos($val, ' ')) {
  2489. list($field, $sort) = explode(' ', $val);
  2490. if (array_key_exists($field, $options['map'])) {
  2491. $options['order'][$options['map'][$field]] = $sort;
  2492. unset($options['order'][$key]);
  2493. }
  2494. } elseif (array_key_exists($val, $options['map'])) {
  2495. $options['order'][$options['map'][$val]] = 'asc';
  2496. unset($options['order'][$key]);
  2497. }
  2498. } elseif (array_key_exists($key, $options['map'])) {
  2499. $options['order'][$options['map'][$key]] = $val;
  2500. unset($options['order'][$key]);
  2501. }
  2502. }
  2503. }
  2504. }
  2505. if (!isset($options['field'])) {
  2506. $options['field'] = '*';
  2507. }
  2508. if (!isset($options['data'])) {
  2509. $options['data'] = [];
  2510. }
  2511. if (!isset($options['strict'])) {
  2512. $options['strict'] = $this->getConfig('fields_strict');
  2513. }
  2514. foreach (['master', 'lock', 'fetch_pdo', 'fetch_sql', 'distinct'] as $name) {
  2515. if (!isset($options[$name])) {
  2516. $options[$name] = false;
  2517. }
  2518. }
  2519. foreach (['join', 'union', 'group', 'having', 'limit', 'order', 'force', 'comment'] as $name) {
  2520. if (!isset($options[$name])) {
  2521. $options[$name] = '';
  2522. }
  2523. }
  2524. if (isset($options['page'])) {
  2525. // 根据页数计算limit
  2526. list($page, $listRows) = $options['page'];
  2527. $page = $page > 0 ? $page : 1;
  2528. $listRows = $listRows > 0 ? $listRows : (is_numeric($options['limit']) ? $options['limit'] : 20);
  2529. $offset = $listRows * ($page - 1);
  2530. $options['limit'] = $offset . ',' . $listRows;
  2531. }
  2532. $this->options = [];
  2533. return $options;
  2534. }
  2535. /**
  2536. * 注册回调方法
  2537. * @access public
  2538. * @param string $event 事件名
  2539. * @param callable $callback 回调方法
  2540. * @return void
  2541. */
  2542. public static function event($event, $callback)
  2543. {
  2544. self::$event[$event] = $callback;
  2545. }
  2546. /**
  2547. * 触发事件
  2548. * @access protected
  2549. * @param string $event 事件名
  2550. * @param mixed $options 当前查询参数
  2551. * @return bool
  2552. */
  2553. protected function trigger($event, $options = [])
  2554. {
  2555. $result = false;
  2556. if (isset(self::$event[$event])) {
  2557. $callback = self::$event[$event];
  2558. $result = call_user_func_array($callback, [$options, $this]);
  2559. }
  2560. return $result;
  2561. }
  2562. /**
  2563. * 获取全部数据
  2564. * @param string $type tree获取树形结构 level获取层级结构
  2565. * @param string $order 排序方式
  2566. * @return array 结构数据
  2567. */
  2568. public function getTreeData($type='tree',$order='',$name='name',$child='id',$parent='pid'){
  2569. // 判断是否需要排序
  2570. if(empty($order)){
  2571. $data=$this->select();
  2572. }else{
  2573. $data=$this->order($order.' is null,'.$order)->select();
  2574. }
  2575. // 获取树形或者结构数据
  2576. if($type=='tree'){
  2577. $data=Data::tree($data,$name,$child,$parent);
  2578. }elseif($type="level"){
  2579. $data=Data::channelLevel($data,0,'&nbsp;',$child);
  2580. }
  2581. return $data;
  2582. }
  2583. }