Query.php 95 KB

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