Query.php 96 KB

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