Query.php 94 KB

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