Query.php 90 KB

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