赛亿官网

Query.php 87KB

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