Query.php 95 KB

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