Query.php 87 KB

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