Query.php 83 KB

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