Query.php 94 KB

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