Query.php 83 KB

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