Query.php 89 KB

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