Query.php 88 KB

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