Query.php 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070
  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. //list_rows
  1382. $listRows = isset($_REQUEST['listrow']) ? (int)$_REQUEST['listrow'] : $listRows;
  1383. /** @var Paginator $class */
  1384. $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\paginator\\driver\\' . ucwords($config['type']);
  1385. $page = isset($config['page']) ? (int) $config['page'] : call_user_func([
  1386. $class,
  1387. 'getCurrentPage',
  1388. ], $config['var_page']);
  1389. $page = $page < 1 ? 1 : $page;
  1390. $config['path'] = isset($config['path']) ? $config['path'] : call_user_func([$class, 'getCurrentPath']);
  1391. if (!isset($total) && !$simple) {
  1392. $options = $this->getOptions();
  1393. unset($this->options['order'], $this->options['limit'], $this->options['page'], $this->options['field']);
  1394. $bind = $this->bind;
  1395. $total = $this->count();
  1396. $results = $this->options($options)->bind($bind)->page($page, $listRows)->select();
  1397. } elseif ($simple) {
  1398. $results = $this->limit(($page - 1) * $listRows, $listRows + 1)->select();
  1399. $total = null;
  1400. } else {
  1401. $results = $this->page($page, $listRows)->select();
  1402. }
  1403. return $class::make($results, $listRows, $page, $total, $simple, $config);
  1404. }
  1405. /**
  1406. * 指定当前操作的数据表
  1407. * @access public
  1408. * @param mixed $table 表名
  1409. * @return $this
  1410. */
  1411. public function table($table)
  1412. {
  1413. if (is_string($table)) {
  1414. if (strpos($table, ')')) {
  1415. // 子查询
  1416. } elseif (strpos($table, ',')) {
  1417. $tables = explode(',', $table);
  1418. $table = [];
  1419. foreach ($tables as $item) {
  1420. list($item, $alias) = explode(' ', trim($item));
  1421. if ($alias) {
  1422. $this->alias([$item => $alias]);
  1423. $table[$item] = $alias;
  1424. } else {
  1425. $table[] = $item;
  1426. }
  1427. }
  1428. } elseif (strpos($table, ' ')) {
  1429. list($table, $alias) = explode(' ', $table);
  1430. $table = [$table => $alias];
  1431. $this->alias($table);
  1432. }
  1433. } else {
  1434. $tables = $table;
  1435. $table = [];
  1436. foreach ($tables as $key => $val) {
  1437. if (is_numeric($key)) {
  1438. $table[] = $val;
  1439. } else {
  1440. $this->alias([$key => $val]);
  1441. $table[$key] = $val;
  1442. }
  1443. }
  1444. }
  1445. $this->options['table'] = $table;
  1446. return $this;
  1447. }
  1448. /**
  1449. * USING支持 用于多表删除
  1450. * @access public
  1451. * @param mixed $using
  1452. * @return $this
  1453. */
  1454. public function using($using)
  1455. {
  1456. $this->options['using'] = $using;
  1457. return $this;
  1458. }
  1459. /**
  1460. * 指定排序 order('id','desc') 或者 order(['id'=>'desc','create_time'=>'desc'])
  1461. * @access public
  1462. * @param string|array $field 排序字段
  1463. * @param string $order 排序
  1464. * @return $this
  1465. */
  1466. public function order($field, $order = null)
  1467. {
  1468. if (empty($field)) {
  1469. return $this;
  1470. } elseif ($field instanceof Expression) {
  1471. $this->options['order'][] = $field;
  1472. return $this;
  1473. }
  1474. if (is_string($field)) {
  1475. if (!empty($this->options['via'])) {
  1476. $field = $this->options['via'] . '.' . $field;
  1477. }
  1478. if (strpos($field, ',')) {
  1479. $field = array_map('trim', explode(',', $field));
  1480. } else {
  1481. $field = empty($order) ? $field : [$field => $order];
  1482. }
  1483. } elseif (!empty($this->options['via'])) {
  1484. foreach ($field as $key => $val) {
  1485. if (is_numeric($key)) {
  1486. $field[$key] = $this->options['via'] . '.' . $val;
  1487. } else {
  1488. $field[$this->options['via'] . '.' . $key] = $val;
  1489. unset($field[$key]);
  1490. }
  1491. }
  1492. }
  1493. if (!isset($this->options['order'])) {
  1494. $this->options['order'] = [];
  1495. }
  1496. if (is_array($field)) {
  1497. $this->options['order'] = array_merge($this->options['order'], $field);
  1498. } else {
  1499. $this->options['order'][] = $field;
  1500. }
  1501. return $this;
  1502. }
  1503. /**
  1504. * 表达式方式指定Field排序
  1505. * @access public
  1506. * @param string $field 排序字段
  1507. * @param array $bind 参数绑定
  1508. * @return $this
  1509. */
  1510. public function orderRaw($field, array $bind = [])
  1511. {
  1512. $this->options['order'][] = $this->raw($field);
  1513. if ($bind) {
  1514. $this->bind($bind);
  1515. }
  1516. return $this;
  1517. }
  1518. /**
  1519. * 查询缓存
  1520. * @access public
  1521. * @param mixed $key 缓存key
  1522. * @param integer|\DateTime $expire 缓存有效期
  1523. * @param string $tag 缓存标签
  1524. * @return $this
  1525. */
  1526. public function cache($key = true, $expire = null, $tag = null)
  1527. {
  1528. // 增加快捷调用方式 cache(10) 等同于 cache(true, 10)
  1529. if ($key instanceof \DateTime || (is_numeric($key) && is_null($expire))) {
  1530. $expire = $key;
  1531. $key = true;
  1532. }
  1533. if (false !== $key) {
  1534. $this->options['cache'] = ['key' => $key, 'expire' => $expire, 'tag' => $tag];
  1535. }
  1536. return $this;
  1537. }
  1538. /**
  1539. * 指定group查询
  1540. * @access public
  1541. * @param string $group GROUP
  1542. * @return $this
  1543. */
  1544. public function group($group)
  1545. {
  1546. $this->options['group'] = $group;
  1547. return $this;
  1548. }
  1549. /**
  1550. * 指定having查询
  1551. * @access public
  1552. * @param string $having having
  1553. * @return $this
  1554. */
  1555. public function having($having)
  1556. {
  1557. $this->options['having'] = $having;
  1558. return $this;
  1559. }
  1560. /**
  1561. * 指定查询lock
  1562. * @access public
  1563. * @param bool|string $lock 是否lock
  1564. * @return $this
  1565. */
  1566. public function lock($lock = false)
  1567. {
  1568. $this->options['lock'] = $lock;
  1569. $this->options['master'] = true;
  1570. return $this;
  1571. }
  1572. /**
  1573. * 指定distinct查询
  1574. * @access public
  1575. * @param string $distinct 是否唯一
  1576. * @return $this
  1577. */
  1578. public function distinct($distinct)
  1579. {
  1580. $this->options['distinct'] = $distinct;
  1581. return $this;
  1582. }
  1583. /**
  1584. * 指定数据表别名
  1585. * @access public
  1586. * @param mixed $alias 数据表别名
  1587. * @return $this
  1588. */
  1589. public function alias($alias)
  1590. {
  1591. if (is_array($alias)) {
  1592. foreach ($alias as $key => $val) {
  1593. if (false !== strpos($key, '__')) {
  1594. $table = $this->parseSqlTable($key);
  1595. } else {
  1596. $table = $key;
  1597. }
  1598. $this->options['alias'][$table] = $val;
  1599. }
  1600. } else {
  1601. if (isset($this->options['table'])) {
  1602. $table = is_array($this->options['table']) ? key($this->options['table']) : $this->options['table'];
  1603. if (false !== strpos($table, '__')) {
  1604. $table = $this->parseSqlTable($table);
  1605. }
  1606. } else {
  1607. $table = $this->getTable();
  1608. }
  1609. $this->options['alias'][$table] = $alias;
  1610. }
  1611. return $this;
  1612. }
  1613. /**
  1614. * 指定强制索引
  1615. * @access public
  1616. * @param string $force 索引名称
  1617. * @return $this
  1618. */
  1619. public function force($force)
  1620. {
  1621. $this->options['force'] = $force;
  1622. return $this;
  1623. }
  1624. /**
  1625. * 查询注释
  1626. * @access public
  1627. * @param string $comment 注释
  1628. * @return $this
  1629. */
  1630. public function comment($comment)
  1631. {
  1632. $this->options['comment'] = $comment;
  1633. return $this;
  1634. }
  1635. /**
  1636. * 获取执行的SQL语句
  1637. * @access public
  1638. * @param boolean $fetch 是否返回sql
  1639. * @return $this
  1640. */
  1641. public function fetchSql($fetch = true)
  1642. {
  1643. $this->options['fetch_sql'] = $fetch;
  1644. return $this;
  1645. }
  1646. /**
  1647. * 不主动获取数据集
  1648. * @access public
  1649. * @param bool $pdo 是否返回 PDOStatement 对象
  1650. * @return $this
  1651. */
  1652. public function fetchPdo($pdo = true)
  1653. {
  1654. $this->options['fetch_pdo'] = $pdo;
  1655. return $this;
  1656. }
  1657. /**
  1658. * 设置从主服务器读取数据
  1659. * @access public
  1660. * @return $this
  1661. */
  1662. public function master()
  1663. {
  1664. $this->options['master'] = true;
  1665. return $this;
  1666. }
  1667. /**
  1668. * 设置是否严格检查字段名
  1669. * @access public
  1670. * @param bool $strict 是否严格检查字段
  1671. * @return $this
  1672. */
  1673. public function strict($strict = true)
  1674. {
  1675. $this->options['strict'] = $strict;
  1676. return $this;
  1677. }
  1678. /**
  1679. * 设置查询数据不存在是否抛出异常
  1680. * @access public
  1681. * @param bool $fail 数据不存在是否抛出异常
  1682. * @return $this
  1683. */
  1684. public function failException($fail = true)
  1685. {
  1686. $this->options['fail'] = $fail;
  1687. return $this;
  1688. }
  1689. /**
  1690. * 设置自增序列名
  1691. * @access public
  1692. * @param string $sequence 自增序列名
  1693. * @return $this
  1694. */
  1695. public function sequence($sequence = null)
  1696. {
  1697. $this->options['sequence'] = $sequence;
  1698. return $this;
  1699. }
  1700. /**
  1701. * 指定数据表主键
  1702. * @access public
  1703. * @param string $pk 主键
  1704. * @return $this
  1705. */
  1706. public function pk($pk)
  1707. {
  1708. $this->pk = $pk;
  1709. return $this;
  1710. }
  1711. /**
  1712. * 查询日期或者时间
  1713. * @access public
  1714. * @param string $field 日期字段名
  1715. * @param string|array $op 比较运算符或者表达式
  1716. * @param string|array $range 比较范围
  1717. * @return $this
  1718. */
  1719. public function whereTime($field, $op, $range = null)
  1720. {
  1721. if (is_null($range)) {
  1722. if (is_array($op)) {
  1723. $range = $op;
  1724. } else {
  1725. // 使用日期表达式
  1726. switch (strtolower($op)) {
  1727. case 'today':
  1728. case 'd':
  1729. $range = ['today', 'tomorrow'];
  1730. break;
  1731. case 'week':
  1732. case 'w':
  1733. $range = ['this week 00:00:00', 'next week 00:00:00'];
  1734. break;
  1735. case 'month':
  1736. case 'm':
  1737. $range = ['first Day of this month 00:00:00', 'first Day of next month 00:00:00'];
  1738. break;
  1739. case 'year':
  1740. case 'y':
  1741. $range = ['this year 1/1', 'next year 1/1'];
  1742. break;
  1743. case 'yesterday':
  1744. $range = ['yesterday', 'today'];
  1745. break;
  1746. case 'last week':
  1747. $range = ['last week 00:00:00', 'this week 00:00:00'];
  1748. break;
  1749. case 'last month':
  1750. $range = ['first Day of last month 00:00:00', 'first Day of this month 00:00:00'];
  1751. break;
  1752. case 'last year':
  1753. $range = ['last year 1/1', 'this year 1/1'];
  1754. break;
  1755. default:
  1756. $range = $op;
  1757. }
  1758. }
  1759. $op = is_array($range) ? 'between' : '>';
  1760. }
  1761. $this->where($field, strtolower($op) . ' time', $range);
  1762. return $this;
  1763. }
  1764. /**
  1765. * 获取数据表信息
  1766. * @access public
  1767. * @param mixed $tableName 数据表名 留空自动获取
  1768. * @param string $fetch 获取信息类型 包括 fields type bind pk
  1769. * @return mixed
  1770. */
  1771. public function getTableInfo($tableName = '', $fetch = '')
  1772. {
  1773. if (!$tableName) {
  1774. $tableName = $this->getTable();
  1775. }
  1776. if (is_array($tableName)) {
  1777. $tableName = key($tableName) ?: current($tableName);
  1778. }
  1779. if (strpos($tableName, ',')) {
  1780. // 多表不获取字段信息
  1781. return false;
  1782. } else {
  1783. $tableName = $this->parseSqlTable($tableName);
  1784. }
  1785. // 修正子查询作为表名的问题
  1786. if (strpos($tableName, ')')) {
  1787. return [];
  1788. }
  1789. list($guid) = explode(' ', $tableName);
  1790. $db = $this->getConfig('database');
  1791. if (!isset(self::$info[$db . '.' . $guid])) {
  1792. if (!strpos($guid, '.')) {
  1793. $schema = $db . '.' . $guid;
  1794. } else {
  1795. $schema = $guid;
  1796. }
  1797. // 读取缓存
  1798. if (!App::$debug && is_file(RUNTIME_PATH . 'schema/' . $schema . '.php')) {
  1799. $info = include RUNTIME_PATH . 'schema/' . $schema . '.php';
  1800. } else {
  1801. $info = $this->connection->getFields($guid);
  1802. }
  1803. $fields = array_keys($info);
  1804. $bind = $type = [];
  1805. foreach ($info as $key => $val) {
  1806. // 记录字段类型
  1807. $type[$key] = $val['type'];
  1808. $bind[$key] = $this->getFieldBindType($val['type']);
  1809. if (!empty($val['primary'])) {
  1810. $pk[] = $key;
  1811. }
  1812. }
  1813. if (isset($pk)) {
  1814. // 设置主键
  1815. $pk = count($pk) > 1 ? $pk : $pk[0];
  1816. } else {
  1817. $pk = null;
  1818. }
  1819. self::$info[$db . '.' . $guid] = ['fields' => $fields, 'type' => $type, 'bind' => $bind, 'pk' => $pk];
  1820. }
  1821. return $fetch ? self::$info[$db . '.' . $guid][$fetch] : self::$info[$db . '.' . $guid];
  1822. }
  1823. /**
  1824. * 获取当前数据表的主键
  1825. * @access public
  1826. * @param string|array $options 数据表名或者查询参数
  1827. * @return string|array
  1828. */
  1829. public function getPk($options = '')
  1830. {
  1831. if (!empty($this->pk)) {
  1832. $pk = $this->pk;
  1833. } else {
  1834. $pk = $this->getTableInfo(is_array($options) && isset($options['table']) ? $options['table'] : $options, 'pk');
  1835. }
  1836. return $pk;
  1837. }
  1838. // 获取当前数据表字段信息
  1839. public function getTableFields($table = '')
  1840. {
  1841. return $this->getTableInfo($table ?: $this->getOptions('table'), 'fields');
  1842. }
  1843. // 获取当前数据表字段类型
  1844. public function getFieldsType($table = '')
  1845. {
  1846. return $this->getTableInfo($table ?: $this->getOptions('table'), 'type');
  1847. }
  1848. // 获取当前数据表绑定信息
  1849. public function getFieldsBind($table = '')
  1850. {
  1851. $types = $this->getFieldsType($table);
  1852. $bind = [];
  1853. if ($types) {
  1854. foreach ($types as $key => $type) {
  1855. $bind[$key] = $this->getFieldBindType($type);
  1856. }
  1857. }
  1858. return $bind;
  1859. }
  1860. /**
  1861. * 获取字段绑定类型
  1862. * @access public
  1863. * @param string $type 字段类型
  1864. * @return integer
  1865. */
  1866. protected function getFieldBindType($type)
  1867. {
  1868. if (0 === strpos($type, 'set') || 0 === strpos($type, 'enum')) {
  1869. $bind = PDO::PARAM_STR;
  1870. } elseif (preg_match('/(int|double|float|decimal|real|numeric|serial|bit)/is', $type)) {
  1871. $bind = PDO::PARAM_INT;
  1872. } elseif (preg_match('/bool/is', $type)) {
  1873. $bind = PDO::PARAM_BOOL;
  1874. } else {
  1875. $bind = PDO::PARAM_STR;
  1876. }
  1877. return $bind;
  1878. }
  1879. /**
  1880. * 参数绑定
  1881. * @access public
  1882. * @param mixed $key 参数名
  1883. * @param mixed $value 绑定变量值
  1884. * @param integer $type 绑定类型
  1885. * @return $this
  1886. */
  1887. public function bind($key, $value = false, $type = PDO::PARAM_STR)
  1888. {
  1889. if (is_array($key)) {
  1890. $this->bind = array_merge($this->bind, $key);
  1891. } else {
  1892. $this->bind[$key] = [$value, $type];
  1893. }
  1894. return $this;
  1895. }
  1896. /**
  1897. * 检测参数是否已经绑定
  1898. * @access public
  1899. * @param string $key 参数名
  1900. * @return bool
  1901. */
  1902. public function isBind($key)
  1903. {
  1904. return isset($this->bind[$key]);
  1905. }
  1906. /**
  1907. * 查询参数赋值
  1908. * @access protected
  1909. * @param array $options 表达式参数
  1910. * @return $this
  1911. */
  1912. protected function options(array $options)
  1913. {
  1914. $this->options = $options;
  1915. return $this;
  1916. }
  1917. /**
  1918. * 获取当前的查询参数
  1919. * @access public
  1920. * @param string $name 参数名
  1921. * @return mixed
  1922. */
  1923. public function getOptions($name = '')
  1924. {
  1925. if ('' === $name) {
  1926. return $this->options;
  1927. } else {
  1928. return isset($this->options[$name]) ? $this->options[$name] : null;
  1929. }
  1930. }
  1931. /**
  1932. * 设置关联查询JOIN预查询
  1933. * @access public
  1934. * @param string|array $with 关联方法名称
  1935. * @return $this
  1936. */
  1937. public function with($with)
  1938. {
  1939. if (empty($with)) {
  1940. return $this;
  1941. }
  1942. if (is_string($with)) {
  1943. $with = explode(',', $with);
  1944. }
  1945. $first = true;
  1946. /** @var Model $class */
  1947. $class = $this->model;
  1948. foreach ($with as $key => $relation) {
  1949. $subRelation = '';
  1950. $closure = false;
  1951. if ($relation instanceof \Closure) {
  1952. // 支持闭包查询过滤关联条件
  1953. $closure = $relation;
  1954. $relation = $key;
  1955. $with[$key] = $key;
  1956. } elseif (is_array($relation)) {
  1957. $subRelation = $relation;
  1958. $relation = $key;
  1959. } elseif (is_string($relation) && strpos($relation, '.')) {
  1960. $with[$key] = $relation;
  1961. list($relation, $subRelation) = explode('.', $relation, 2);
  1962. }
  1963. /** @var Relation $model */
  1964. $relation = Loader::parseName($relation, 1, false);
  1965. $model = $class->$relation();
  1966. if ($model instanceof OneToOne && 0 == $model->getEagerlyType()) {
  1967. $model->eagerly($this, $relation, $subRelation, $closure, $first);
  1968. $first = false;
  1969. } elseif ($closure) {
  1970. $with[$key] = $closure;
  1971. }
  1972. }
  1973. $this->via();
  1974. if (isset($this->options['with'])) {
  1975. $this->options['with'] = array_merge($this->options['with'], $with);
  1976. } else {
  1977. $this->options['with'] = $with;
  1978. }
  1979. return $this;
  1980. }
  1981. /**
  1982. * 关联统计
  1983. * @access public
  1984. * @param string|array $relation 关联方法名
  1985. * @param bool $subQuery 是否使用子查询
  1986. * @return $this
  1987. */
  1988. public function withCount($relation, $subQuery = true)
  1989. {
  1990. if (!$subQuery) {
  1991. $this->options['with_count'] = $relation;
  1992. } else {
  1993. $relations = is_string($relation) ? explode(',', $relation) : $relation;
  1994. if (!isset($this->options['field'])) {
  1995. $this->field('*');
  1996. }
  1997. foreach ($relations as $key => $relation) {
  1998. $closure = $name = null;
  1999. if ($relation instanceof \Closure) {
  2000. $closure = $relation;
  2001. $relation = $key;
  2002. } elseif (!is_int($key)) {
  2003. $name = $relation;
  2004. $relation = $key;
  2005. }
  2006. $relation = Loader::parseName($relation, 1, false);
  2007. $count = '(' . $this->model->$relation()->getRelationCountQuery($closure, $name) . ')';
  2008. if (empty($name)) {
  2009. $name = Loader::parseName($relation) . '_count';
  2010. }
  2011. $this->field([$count => $name]);
  2012. }
  2013. }
  2014. return $this;
  2015. }
  2016. /**
  2017. * 关联预加载中 获取关联指定字段值
  2018. * example:
  2019. * Model::with(['relation' => function($query){
  2020. * $query->withField("id,name");
  2021. * }])
  2022. *
  2023. * @param string | array $field 指定获取的字段
  2024. * @return $this
  2025. */
  2026. public function withField($field)
  2027. {
  2028. $this->options['with_field'] = $field;
  2029. return $this;
  2030. }
  2031. /**
  2032. * 设置当前字段添加的表别名
  2033. * @access public
  2034. * @param string $via
  2035. * @return $this
  2036. */
  2037. public function via($via = '')
  2038. {
  2039. $this->options['via'] = $via;
  2040. return $this;
  2041. }
  2042. /**
  2043. * 设置关联查询
  2044. * @access public
  2045. * @param string|array $relation 关联名称
  2046. * @return $this
  2047. */
  2048. public function relation($relation)
  2049. {
  2050. if (empty($relation)) {
  2051. return $this;
  2052. }
  2053. if (is_string($relation)) {
  2054. $relation = explode(',', $relation);
  2055. }
  2056. if (isset($this->options['relation'])) {
  2057. $this->options['relation'] = array_merge($this->options['relation'], $relation);
  2058. } else {
  2059. $this->options['relation'] = $relation;
  2060. }
  2061. return $this;
  2062. }
  2063. /**
  2064. * 把主键值转换为查询条件 支持复合主键
  2065. * @access public
  2066. * @param array|string $data 主键数据
  2067. * @param mixed $options 表达式参数
  2068. * @return void
  2069. * @throws Exception
  2070. */
  2071. protected function parsePkWhere($data, &$options)
  2072. {
  2073. $pk = $this->getPk($options);
  2074. // 获取当前数据表
  2075. $table = is_array($options['table']) ? key($options['table']) : $options['table'];
  2076. if (!empty($options['alias'][$table])) {
  2077. $alias = $options['alias'][$table];
  2078. }
  2079. if (is_string($pk)) {
  2080. $key = isset($alias) ? $alias . '.' . $pk : $pk;
  2081. // 根据主键查询
  2082. if (is_array($data)) {
  2083. $where[$key] = isset($data[$pk]) ? $data[$pk] : ['in', $data];
  2084. } else {
  2085. $where[$key] = strpos($data, ',') ? ['IN', $data] : $data;
  2086. }
  2087. } elseif (is_array($pk) && is_array($data) && !empty($data)) {
  2088. // 根据复合主键查询
  2089. foreach ($pk as $key) {
  2090. if (isset($data[$key])) {
  2091. $attr = isset($alias) ? $alias . '.' . $key : $key;
  2092. $where[$attr] = $data[$key];
  2093. } else {
  2094. throw new Exception('miss complex primary data');
  2095. }
  2096. }
  2097. }
  2098. if (!empty($where)) {
  2099. if (isset($options['where']['AND'])) {
  2100. $options['where']['AND'] = array_merge($options['where']['AND'], $where);
  2101. } else {
  2102. $options['where']['AND'] = $where;
  2103. }
  2104. }
  2105. return;
  2106. }
  2107. /**
  2108. * 插入记录
  2109. * @access public
  2110. * @param mixed $data 数据
  2111. * @param boolean $replace 是否replace
  2112. * @param boolean $getLastInsID 返回自增主键
  2113. * @param string $sequence 自增序列名
  2114. * @return integer|string
  2115. */
  2116. public function insert(array $data = [], $replace = false, $getLastInsID = false, $sequence = null)
  2117. {
  2118. // 分析查询表达式
  2119. $options = $this->parseExpress();
  2120. $data = array_merge($options['data'], $data);
  2121. // 生成SQL语句
  2122. $sql = $this->builder->insert($data, $options, $replace);
  2123. // 获取参数绑定
  2124. $bind = $this->getBind();
  2125. if ($options['fetch_sql']) {
  2126. // 获取实际执行的SQL语句
  2127. return $this->connection->getRealSql($sql, $bind);
  2128. }
  2129. // 执行操作
  2130. $result = 0 === $sql ? 0 : $this->execute($sql, $bind, $this);
  2131. if ($result) {
  2132. $sequence = $sequence ?: (isset($options['sequence']) ? $options['sequence'] : null);
  2133. $lastInsId = $this->getLastInsID($sequence);
  2134. if ($lastInsId) {
  2135. $pk = $this->getPk($options);
  2136. if (is_string($pk)) {
  2137. $data[$pk] = $lastInsId;
  2138. }
  2139. }
  2140. $options['data'] = $data;
  2141. $this->trigger('after_insert', $options);
  2142. if ($getLastInsID) {
  2143. return $lastInsId;
  2144. }
  2145. }
  2146. return $result;
  2147. }
  2148. /**
  2149. * 插入记录并获取自增ID
  2150. * @access public
  2151. * @param mixed $data 数据
  2152. * @param boolean $replace 是否replace
  2153. * @param string $sequence 自增序列名
  2154. * @return integer|string
  2155. */
  2156. public function insertGetId(array $data, $replace = false, $sequence = null)
  2157. {
  2158. return $this->insert($data, $replace, true, $sequence);
  2159. }
  2160. /**
  2161. * 批量插入记录
  2162. * @access public
  2163. * @param mixed $dataSet 数据集
  2164. * @param boolean $replace 是否replace
  2165. * @param integer $limit 每次写入数据限制
  2166. * @return integer|string
  2167. */
  2168. public function insertAll(array $dataSet, $replace = false, $limit = null)
  2169. {
  2170. // 分析查询表达式
  2171. $options = $this->parseExpress();
  2172. if (!is_array(reset($dataSet))) {
  2173. return false;
  2174. }
  2175. // 生成SQL语句
  2176. if (is_null($limit)) {
  2177. $sql = $this->builder->insertAll($dataSet, $options, $replace);
  2178. } else {
  2179. $array = array_chunk($dataSet, $limit, true);
  2180. foreach ($array as $item) {
  2181. $sql[] = $this->builder->insertAll($item, $options, $replace);
  2182. }
  2183. }
  2184. // 获取参数绑定
  2185. $bind = $this->getBind();
  2186. if ($options['fetch_sql']) {
  2187. // 获取实际执行的SQL语句
  2188. return $this->connection->getRealSql($sql, $bind);
  2189. } elseif (is_array($sql)) {
  2190. // 执行操作
  2191. return $this->batchQuery($sql, $bind, $this);
  2192. } else {
  2193. // 执行操作
  2194. return $this->execute($sql, $bind, $this);
  2195. }
  2196. }
  2197. /**
  2198. * 通过Select方式插入记录
  2199. * @access public
  2200. * @param string $fields 要插入的数据表字段名
  2201. * @param string $table 要插入的数据表名
  2202. * @return integer|string
  2203. * @throws PDOException
  2204. */
  2205. public function selectInsert($fields, $table)
  2206. {
  2207. // 分析查询表达式
  2208. $options = $this->parseExpress();
  2209. // 生成SQL语句
  2210. $table = $this->parseSqlTable($table);
  2211. $sql = $this->builder->selectInsert($fields, $table, $options);
  2212. // 获取参数绑定
  2213. $bind = $this->getBind();
  2214. if ($options['fetch_sql']) {
  2215. // 获取实际执行的SQL语句
  2216. return $this->connection->getRealSql($sql, $bind);
  2217. } else {
  2218. // 执行操作
  2219. return $this->execute($sql, $bind, $this);
  2220. }
  2221. }
  2222. /**
  2223. * 更新记录
  2224. * @access public
  2225. * @param mixed $data 数据
  2226. * @return integer|string
  2227. * @throws Exception
  2228. * @throws PDOException
  2229. */
  2230. public function update(array $data = [])
  2231. {
  2232. $options = $this->parseExpress();
  2233. $data = array_merge($options['data'], $data);
  2234. $pk = $this->getPk($options);
  2235. if (isset($options['cache']) && is_string($options['cache']['key'])) {
  2236. $key = $options['cache']['key'];
  2237. }
  2238. if (empty($options['where'])) {
  2239. // 如果存在主键数据 则自动作为更新条件
  2240. if (is_string($pk) && isset($data[$pk])) {
  2241. $where[$pk] = $data[$pk];
  2242. if (!isset($key)) {
  2243. $key = 'think:' . $options['table'] . '|' . $data[$pk];
  2244. }
  2245. unset($data[$pk]);
  2246. } elseif (is_array($pk)) {
  2247. // 增加复合主键支持
  2248. foreach ($pk as $field) {
  2249. if (isset($data[$field])) {
  2250. $where[$field] = $data[$field];
  2251. } else {
  2252. // 如果缺少复合主键数据则不执行
  2253. throw new Exception('miss complex primary data');
  2254. }
  2255. unset($data[$field]);
  2256. }
  2257. }
  2258. if (!isset($where)) {
  2259. // 如果没有任何更新条件则不执行
  2260. throw new Exception('miss update condition');
  2261. } else {
  2262. $options['where']['AND'] = $where;
  2263. }
  2264. } elseif (!isset($key) && is_string($pk) && isset($options['where']['AND'][$pk])) {
  2265. $key = $this->getCacheKey($options['where']['AND'][$pk], $options, $this->bind);
  2266. }
  2267. // 生成UPDATE SQL语句
  2268. $sql = $this->builder->update($data, $options);
  2269. // 获取参数绑定
  2270. $bind = $this->getBind();
  2271. if ($options['fetch_sql']) {
  2272. // 获取实际执行的SQL语句
  2273. return $this->connection->getRealSql($sql, $bind);
  2274. } else {
  2275. // 检测缓存
  2276. if (isset($key) && Cache::get($key)) {
  2277. // 删除缓存
  2278. Cache::rm($key);
  2279. } elseif (!empty($options['cache']['tag'])) {
  2280. Cache::clear($options['cache']['tag']);
  2281. }
  2282. // 执行操作
  2283. $result = '' == $sql ? 0 : $this->execute($sql, $bind, $this);
  2284. if ($result) {
  2285. if (is_string($pk) && isset($where[$pk])) {
  2286. $data[$pk] = $where[$pk];
  2287. } elseif (is_string($pk) && isset($key) && strpos($key, '|')) {
  2288. list($a, $val) = explode('|', $key);
  2289. $data[$pk] = $val;
  2290. }
  2291. $options['data'] = $data;
  2292. $this->trigger('after_update', $options);
  2293. }
  2294. return $result;
  2295. }
  2296. }
  2297. /**
  2298. * 执行查询但只返回PDOStatement对象
  2299. * @access public
  2300. * @return \PDOStatement|string
  2301. */
  2302. public function getPdo()
  2303. {
  2304. // 分析查询表达式
  2305. $options = $this->parseExpress();
  2306. // 生成查询SQL
  2307. $sql = $this->builder->select($options);
  2308. // 获取参数绑定
  2309. $bind = $this->getBind();
  2310. if ($options['fetch_sql']) {
  2311. // 获取实际执行的SQL语句
  2312. return $this->connection->getRealSql($sql, $bind);
  2313. }
  2314. // 执行查询操作
  2315. return $this->query($sql, $bind, $options['master'], true);
  2316. }
  2317. /**
  2318. * 查找记录
  2319. * @access public
  2320. * @param array|string|Query|\Closure $data
  2321. * @return Collection|false|\PDOStatement|string
  2322. * @throws DbException
  2323. * @throws ModelNotFoundException
  2324. * @throws DataNotFoundException
  2325. */
  2326. public function select($data = null)
  2327. {
  2328. if ($data instanceof Query) {
  2329. return $data->select();
  2330. } elseif ($data instanceof \Closure) {
  2331. call_user_func_array($data, [ & $this]);
  2332. $data = null;
  2333. }
  2334. // 分析查询表达式
  2335. $options = $this->parseExpress();
  2336. if (false === $data) {
  2337. // 用于子查询 不查询只返回SQL
  2338. $options['fetch_sql'] = true;
  2339. } elseif (!is_null($data)) {
  2340. // 主键条件分析
  2341. $this->parsePkWhere($data, $options);
  2342. }
  2343. $resultSet = false;
  2344. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  2345. // 判断查询缓存
  2346. $cache = $options['cache'];
  2347. unset($options['cache']);
  2348. $key = is_string($cache['key']) ? $cache['key'] : md5($this->connection->getConfig('database') . '.' . serialize($options) . serialize($this->bind));
  2349. $resultSet = Cache::get($key);
  2350. }
  2351. if (false === $resultSet) {
  2352. // 生成查询SQL
  2353. $sql = $this->builder->select($options);
  2354. // 获取参数绑定
  2355. $bind = $this->getBind();
  2356. if ($options['fetch_sql']) {
  2357. // 获取实际执行的SQL语句
  2358. return $this->connection->getRealSql($sql, $bind);
  2359. }
  2360. $options['data'] = $data;
  2361. if ($resultSet = $this->trigger('before_select', $options)) {
  2362. } else {
  2363. // 执行查询操作
  2364. $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']);
  2365. if ($resultSet instanceof \PDOStatement) {
  2366. // 返回PDOStatement对象
  2367. return $resultSet;
  2368. }
  2369. }
  2370. if (isset($cache) && false !== $resultSet) {
  2371. // 缓存数据集
  2372. $this->cacheData($key, $resultSet, $cache);
  2373. }
  2374. }
  2375. // 数据列表读取后的处理
  2376. if (!empty($this->model)) {
  2377. // 生成模型对象
  2378. if (count($resultSet) > 0) {
  2379. foreach ($resultSet as $key => $result) {
  2380. /** @var Model $model */
  2381. $model = $this->model->newInstance($result);
  2382. $model->isUpdate(true);
  2383. // 关联查询
  2384. if (!empty($options['relation'])) {
  2385. $model->relationQuery($options['relation']);
  2386. }
  2387. // 关联统计
  2388. if (!empty($options['with_count'])) {
  2389. $model->relationCount($model, $options['with_count']);
  2390. }
  2391. $resultSet[$key] = $model;
  2392. }
  2393. if (!empty($options['with'])) {
  2394. // 预载入
  2395. $model->eagerlyResultSet($resultSet, $options['with']);
  2396. }
  2397. // 模型数据集转换
  2398. $resultSet = $model->toCollection($resultSet);
  2399. } else {
  2400. $resultSet = $this->model->toCollection($resultSet);
  2401. }
  2402. } elseif ('collection' == $this->connection->getConfig('resultset_type')) {
  2403. // 返回Collection对象
  2404. $resultSet = new Collection($resultSet);
  2405. }
  2406. // 返回结果处理
  2407. if (!empty($options['fail']) && count($resultSet) == 0) {
  2408. $this->throwNotFound($options);
  2409. }
  2410. return $resultSet;
  2411. }
  2412. /**
  2413. * 缓存数据
  2414. * @access public
  2415. * @param string $key 缓存标识
  2416. * @param mixed $data 缓存数据
  2417. * @param array $config 缓存参数
  2418. */
  2419. protected function cacheData($key, $data, $config = [])
  2420. {
  2421. if (isset($config['tag'])) {
  2422. Cache::tag($config['tag'])->set($key, $data, $config['expire']);
  2423. } else {
  2424. Cache::set($key, $data, $config['expire']);
  2425. }
  2426. }
  2427. /**
  2428. * 生成缓存标识
  2429. * @access public
  2430. * @param mixed $value 缓存数据
  2431. * @param array $options 缓存参数
  2432. * @param array $bind 绑定参数
  2433. * @return string
  2434. */
  2435. protected function getCacheKey($value, $options, $bind = [])
  2436. {
  2437. if (is_scalar($value)) {
  2438. $data = $value;
  2439. } elseif (is_array($value) && is_string($value[0]) && 'eq' == strtolower($value[0])) {
  2440. $data = $value[1];
  2441. }
  2442. $prefix = $this->connection->getConfig('database') . '.';
  2443. if (isset($data)) {
  2444. return 'think:' . $prefix . (is_array($options['table']) ? key($options['table']) : $options['table']) . '|' . $data;
  2445. }
  2446. try {
  2447. return md5($prefix . serialize($options) . serialize($bind));
  2448. } catch (\Exception $e) {
  2449. throw new Exception('closure not support cache(true)');
  2450. }
  2451. }
  2452. /**
  2453. * 查找单条记录
  2454. * @access public
  2455. * @param array|string|Query|\Closure $data
  2456. * @return array|false|\PDOStatement|string|Model
  2457. * @throws DbException
  2458. * @throws ModelNotFoundException
  2459. * @throws DataNotFoundException
  2460. */
  2461. public function find($data = null)
  2462. {
  2463. if ($data instanceof Query) {
  2464. return $data->find();
  2465. } elseif ($data instanceof \Closure) {
  2466. call_user_func_array($data, [ & $this]);
  2467. $data = null;
  2468. }
  2469. // 分析查询表达式
  2470. $options = $this->parseExpress();
  2471. $pk = $this->getPk($options);
  2472. if (!is_null($data)) {
  2473. // AR模式分析主键条件
  2474. $this->parsePkWhere($data, $options);
  2475. } elseif (!empty($options['cache']) && true === $options['cache']['key'] && is_string($pk) && isset($options['where']['AND'][$pk])) {
  2476. $key = $this->getCacheKey($options['where']['AND'][$pk], $options, $this->bind);
  2477. }
  2478. $options['limit'] = 1;
  2479. $result = false;
  2480. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  2481. // 判断查询缓存
  2482. $cache = $options['cache'];
  2483. if (true === $cache['key'] && !is_null($data) && !is_array($data)) {
  2484. $key = 'think:' . $this->connection->getConfig('database') . '.' . (is_array($options['table']) ? key($options['table']) : $options['table']) . '|' . $data;
  2485. } elseif (is_string($cache['key'])) {
  2486. $key = $cache['key'];
  2487. } elseif (!isset($key)) {
  2488. $key = md5($this->connection->getConfig('database') . '.' . serialize($options) . serialize($this->bind));
  2489. }
  2490. $result = Cache::get($key);
  2491. }
  2492. if (false === $result) {
  2493. // 生成查询SQL
  2494. $sql = $this->builder->select($options);
  2495. // 获取参数绑定
  2496. $bind = $this->getBind();
  2497. if ($options['fetch_sql']) {
  2498. // 获取实际执行的SQL语句
  2499. return $this->connection->getRealSql($sql, $bind);
  2500. }
  2501. if (is_string($pk)) {
  2502. if (!is_array($data)) {
  2503. if (isset($key) && strpos($key, '|')) {
  2504. list($a, $val) = explode('|', $key);
  2505. $item[$pk] = $val;
  2506. } else {
  2507. $item[$pk] = $data;
  2508. }
  2509. $data = $item;
  2510. }
  2511. }
  2512. $options['data'] = $data;
  2513. // 事件回调
  2514. if ($result = $this->trigger('before_find', $options)) {
  2515. } else {
  2516. // 执行查询
  2517. $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']);
  2518. if ($resultSet instanceof \PDOStatement) {
  2519. // 返回PDOStatement对象
  2520. return $resultSet;
  2521. }
  2522. $result = isset($resultSet[0]) ? $resultSet[0] : null;
  2523. }
  2524. if (isset($cache) && $result) {
  2525. // 缓存数据
  2526. $this->cacheData($key, $result, $cache);
  2527. }
  2528. }
  2529. // 数据处理
  2530. if (!empty($result)) {
  2531. if (!empty($this->model)) {
  2532. // 返回模型对象
  2533. $result = $this->model->newInstance($result);
  2534. $result->isUpdate(true, isset($options['where']['AND']) ? $options['where']['AND'] : null);
  2535. // 关联查询
  2536. if (!empty($options['relation'])) {
  2537. $result->relationQuery($options['relation']);
  2538. }
  2539. // 预载入查询
  2540. if (!empty($options['with'])) {
  2541. $result->eagerlyResult($result, $options['with']);
  2542. }
  2543. // 关联统计
  2544. if (!empty($options['with_count'])) {
  2545. $result->relationCount($result, $options['with_count']);
  2546. }
  2547. }
  2548. } elseif (!empty($options['fail'])) {
  2549. $this->throwNotFound($options);
  2550. }
  2551. return $result;
  2552. }
  2553. /**
  2554. * 查询失败 抛出异常
  2555. * @access public
  2556. * @param array $options 查询参数
  2557. * @throws ModelNotFoundException
  2558. * @throws DataNotFoundException
  2559. */
  2560. protected function throwNotFound($options = [])
  2561. {
  2562. if (!empty($this->model)) {
  2563. $class = get_class($this->model);
  2564. throw new ModelNotFoundException('model data Not Found:' . $class, $class, $options);
  2565. } else {
  2566. $table = is_array($options['table']) ? key($options['table']) : $options['table'];
  2567. throw new DataNotFoundException('table data not Found:' . $table, $table, $options);
  2568. }
  2569. }
  2570. /**
  2571. * 查找多条记录 如果不存在则抛出异常
  2572. * @access public
  2573. * @param array|string|Query|\Closure $data
  2574. * @return array|\PDOStatement|string|Model
  2575. * @throws DbException
  2576. * @throws ModelNotFoundException
  2577. * @throws DataNotFoundException
  2578. */
  2579. public function selectOrFail($data = null)
  2580. {
  2581. return $this->failException(true)->select($data);
  2582. }
  2583. /**
  2584. * 查找单条记录 如果不存在则抛出异常
  2585. * @access public
  2586. * @param array|string|Query|\Closure $data
  2587. * @return array|\PDOStatement|string|Model
  2588. * @throws DbException
  2589. * @throws ModelNotFoundException
  2590. * @throws DataNotFoundException
  2591. */
  2592. public function findOrFail($data = null)
  2593. {
  2594. return $this->failException(true)->find($data);
  2595. }
  2596. /**
  2597. * 分批数据返回处理
  2598. * @access public
  2599. * @param integer $count 每次处理的数据数量
  2600. * @param callable $callback 处理回调方法
  2601. * @param string $column 分批处理的字段名
  2602. * @param string $order 排序规则
  2603. * @return boolean
  2604. * @throws \LogicException
  2605. */
  2606. public function chunk($count, $callback, $column = null, $order = 'asc')
  2607. {
  2608. $options = $this->getOptions();
  2609. if (empty($options['table'])) {
  2610. $options['table'] = $this->getTable();
  2611. }
  2612. $column = $column ?: $this->getPk($options);
  2613. if (isset($options['order'])) {
  2614. if (App::$debug) {
  2615. throw new \LogicException('chunk not support call order');
  2616. }
  2617. unset($options['order']);
  2618. }
  2619. $bind = $this->bind;
  2620. if (is_array($column)) {
  2621. $times = 1;
  2622. $query = $this->options($options)->page($times, $count);
  2623. } else {
  2624. if (strpos($column, '.')) {
  2625. list($alias, $key) = explode('.', $column);
  2626. } else {
  2627. $key = $column;
  2628. }
  2629. $query = $this->options($options)->limit($count);
  2630. }
  2631. $resultSet = $query->order($column, $order)->select();
  2632. while (count($resultSet) > 0) {
  2633. if ($resultSet instanceof Collection) {
  2634. $resultSet = $resultSet->all();
  2635. }
  2636. if (false === call_user_func($callback, $resultSet)) {
  2637. return false;
  2638. }
  2639. if (is_array($column)) {
  2640. $times++;
  2641. $query = $this->options($options)->page($times, $count);
  2642. } else {
  2643. $end = end($resultSet);
  2644. $lastId = is_array($end) ? $end[$key] : $end->getData($key);
  2645. $query = $this->options($options)
  2646. ->limit($count)
  2647. ->where($column, 'asc' == strtolower($order) ? '>' : '<', $lastId);
  2648. }
  2649. $resultSet = $query->bind($bind)->order($column, $order)->select();
  2650. }
  2651. return true;
  2652. }
  2653. /**
  2654. * 获取绑定的参数 并清空
  2655. * @access public
  2656. * @return array
  2657. */
  2658. public function getBind()
  2659. {
  2660. $bind = $this->bind;
  2661. $this->bind = [];
  2662. return $bind;
  2663. }
  2664. /**
  2665. * 创建子查询SQL
  2666. * @access public
  2667. * @param bool $sub
  2668. * @return string
  2669. * @throws DbException
  2670. */
  2671. public function buildSql($sub = true)
  2672. {
  2673. return $sub ? '( ' . $this->select(false) . ' )' : $this->select(false);
  2674. }
  2675. /**
  2676. * 删除记录
  2677. * @access public
  2678. * @param mixed $data 表达式 true 表示强制删除
  2679. * @return int
  2680. * @throws Exception
  2681. * @throws PDOException
  2682. */
  2683. public function delete($data = null)
  2684. {
  2685. // 分析查询表达式
  2686. $options = $this->parseExpress();
  2687. $pk = $this->getPk($options);
  2688. if (isset($options['cache']) && is_string($options['cache']['key'])) {
  2689. $key = $options['cache']['key'];
  2690. }
  2691. if (!is_null($data) && true !== $data) {
  2692. if (!isset($key) && !is_array($data)) {
  2693. // 缓存标识
  2694. $key = 'think:' . $options['table'] . '|' . $data;
  2695. }
  2696. // AR模式分析主键条件
  2697. $this->parsePkWhere($data, $options);
  2698. } elseif (!isset($key) && is_string($pk) && isset($options['where']['AND'][$pk])) {
  2699. $key = $this->getCacheKey($options['where']['AND'][$pk], $options, $this->bind);
  2700. }
  2701. if (true !== $data && empty($options['where'])) {
  2702. // 如果条件为空 不进行删除操作 除非设置 1=1
  2703. throw new Exception('delete without condition');
  2704. }
  2705. // 生成删除SQL语句
  2706. $sql = $this->builder->delete($options);
  2707. // 获取参数绑定
  2708. $bind = $this->getBind();
  2709. if ($options['fetch_sql']) {
  2710. // 获取实际执行的SQL语句
  2711. return $this->connection->getRealSql($sql, $bind);
  2712. }
  2713. // 检测缓存
  2714. if (isset($key) && Cache::get($key)) {
  2715. // 删除缓存
  2716. Cache::rm($key);
  2717. } elseif (!empty($options['cache']['tag'])) {
  2718. Cache::clear($options['cache']['tag']);
  2719. }
  2720. // 执行操作
  2721. $result = $this->execute($sql, $bind, $this);
  2722. if ($result) {
  2723. if (!is_array($data) && is_string($pk) && isset($key) && strpos($key, '|')) {
  2724. list($a, $val) = explode('|', $key);
  2725. $item[$pk] = $val;
  2726. $data = $item;
  2727. }
  2728. $options['data'] = $data;
  2729. $this->trigger('after_delete', $options);
  2730. }
  2731. return $result;
  2732. }
  2733. /**
  2734. * 分析表达式(可用于查询或者写入操作)
  2735. * @access protected
  2736. * @return array
  2737. */
  2738. protected function parseExpress()
  2739. {
  2740. $options = $this->options;
  2741. // 获取数据表
  2742. if (empty($options['table'])) {
  2743. $options['table'] = $this->getTable();
  2744. }
  2745. if (!isset($options['where'])) {
  2746. $options['where'] = [];
  2747. } elseif (isset($options['view'])) {
  2748. // 视图查询条件处理
  2749. foreach (['AND', 'OR'] as $logic) {
  2750. if (isset($options['where'][$logic])) {
  2751. foreach ($options['where'][$logic] as $key => $val) {
  2752. if (array_key_exists($key, $options['map'])) {
  2753. $options['where'][$logic][$options['map'][$key]] = $val;
  2754. unset($options['where'][$logic][$key]);
  2755. }
  2756. }
  2757. }
  2758. }
  2759. if (isset($options['order'])) {
  2760. // 视图查询排序处理
  2761. if (is_string($options['order'])) {
  2762. $options['order'] = explode(',', $options['order']);
  2763. }
  2764. foreach ($options['order'] as $key => $val) {
  2765. if (is_numeric($key)) {
  2766. if (strpos($val, ' ')) {
  2767. list($field, $sort) = explode(' ', $val);
  2768. if (array_key_exists($field, $options['map'])) {
  2769. $options['order'][$options['map'][$field]] = $sort;
  2770. unset($options['order'][$key]);
  2771. }
  2772. } elseif (array_key_exists($val, $options['map'])) {
  2773. $options['order'][$options['map'][$val]] = 'asc';
  2774. unset($options['order'][$key]);
  2775. }
  2776. } elseif (array_key_exists($key, $options['map'])) {
  2777. $options['order'][$options['map'][$key]] = $val;
  2778. unset($options['order'][$key]);
  2779. }
  2780. }
  2781. }
  2782. }
  2783. if (!isset($options['field'])) {
  2784. $options['field'] = '*';
  2785. }
  2786. if (!isset($options['data'])) {
  2787. $options['data'] = [];
  2788. }
  2789. if (!isset($options['strict'])) {
  2790. $options['strict'] = $this->getConfig('fields_strict');
  2791. }
  2792. foreach (['master', 'lock', 'fetch_pdo', 'fetch_sql', 'distinct'] as $name) {
  2793. if (!isset($options[$name])) {
  2794. $options[$name] = false;
  2795. }
  2796. }
  2797. if (isset(static::$readMaster['*']) || (is_string($options['table']) && isset(static::$readMaster[$options['table']]))) {
  2798. $options['master'] = true;
  2799. }
  2800. foreach (['join', 'union', 'group', 'having', 'limit', 'order', 'force', 'comment'] as $name) {
  2801. if (!isset($options[$name])) {
  2802. $options[$name] = '';
  2803. }
  2804. }
  2805. if (isset($options['page'])) {
  2806. // 根据页数计算limit
  2807. list($page, $listRows) = $options['page'];
  2808. $page = $page > 0 ? $page : 1;
  2809. $listRows = $listRows > 0 ? $listRows : (is_numeric($options['limit']) ? $options['limit'] : 20);
  2810. $offset = $listRows * ($page - 1);
  2811. $options['limit'] = $offset . ',' . $listRows;
  2812. }
  2813. $this->options = [];
  2814. return $options;
  2815. }
  2816. /**
  2817. * 注册回调方法
  2818. * @access public
  2819. * @param string $event 事件名
  2820. * @param callable $callback 回调方法
  2821. * @return void
  2822. */
  2823. public static function event($event, $callback)
  2824. {
  2825. self::$event[$event] = $callback;
  2826. }
  2827. /**
  2828. * 触发事件
  2829. * @access protected
  2830. * @param string $event 事件名
  2831. * @param mixed $params 额外参数
  2832. * @return bool
  2833. */
  2834. protected function trigger($event, $params = [])
  2835. {
  2836. $result = false;
  2837. if (isset(self::$event[$event])) {
  2838. $callback = self::$event[$event];
  2839. $result = call_user_func_array($callback, [$params, $this]);
  2840. }
  2841. return $result;
  2842. }
  2843. }