Query.php 95 KB

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