Açıklama Yok
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Query.php 105KB

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