Query.php 95 KB

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