Query.php 94 KB

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