Query.php 105 KB

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