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