Query.php 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854
  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 Model $model 模型对象
  58. */
  59. public function __construct(Connection $connection = null, $model = null)
  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 Model|null
  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 = $join;
  669. } else {
  670. $join = trim($join);
  671. if (false !== strpos($join, '(')) {
  672. // 使用子查询
  673. $table = $join;
  674. } else {
  675. $prefix = $this->prefix;
  676. if (strpos($join, ' ')) {
  677. // 使用别名
  678. list($table, $alias) = explode(' ', $join);
  679. } else {
  680. $table = $join;
  681. if (false === strpos($join, '.') && 0 !== strpos($join, '__')) {
  682. $alias = $join;
  683. }
  684. }
  685. if ($prefix && false === strpos($table, '.') && 0 !== strpos($table, $prefix) && 0 !== strpos($table, '__')) {
  686. $table = $this->getTable($table);
  687. }
  688. }
  689. if (isset($alias) && $table != $alias) {
  690. $table = [$table => $alias];
  691. }
  692. }
  693. return $table;
  694. }
  695. /**
  696. * 查询SQL组装 union
  697. * @access public
  698. * @param mixed $union
  699. * @param boolean $all
  700. * @return $this
  701. */
  702. public function union($union, $all = false)
  703. {
  704. $this->options['union']['type'] = $all ? 'UNION ALL' : 'UNION';
  705. if (is_array($union)) {
  706. $this->options['union'] = array_merge($this->options['union'], $union);
  707. } else {
  708. $this->options['union'][] = $union;
  709. }
  710. return $this;
  711. }
  712. /**
  713. * 指定查询字段 支持字段排除和指定数据表
  714. * @access public
  715. * @param mixed $field
  716. * @param boolean $except 是否排除
  717. * @param string $tableName 数据表名
  718. * @param string $prefix 字段前缀
  719. * @param string $alias 别名前缀
  720. * @return $this
  721. */
  722. public function field($field, $except = false, $tableName = '', $prefix = '', $alias = '')
  723. {
  724. if (empty($field)) {
  725. return $this;
  726. }
  727. if (is_string($field)) {
  728. $field = array_map('trim', explode(',', $field));
  729. }
  730. if (true === $field) {
  731. // 获取全部字段
  732. $fields = $this->getTableInfo($tableName ?: (isset($this->options['table']) ? $this->options['table'] : ''), 'fields');
  733. $field = $fields ?: ['*'];
  734. } elseif ($except) {
  735. // 字段排除
  736. $fields = $this->getTableInfo($tableName ?: (isset($this->options['table']) ? $this->options['table'] : ''), 'fields');
  737. $field = $fields ? array_diff($fields, $field) : $field;
  738. }
  739. if ($tableName) {
  740. // 添加统一的前缀
  741. $prefix = $prefix ?: $tableName;
  742. foreach ($field as $key => $val) {
  743. if (is_numeric($key)) {
  744. $val = $prefix . '.' . $val . ($alias ? ' AS ' . $alias . $val : '');
  745. }
  746. $field[$key] = $val;
  747. }
  748. }
  749. if (isset($this->options['field'])) {
  750. $field = array_merge($this->options['field'], $field);
  751. }
  752. $this->options['field'] = array_unique($field);
  753. return $this;
  754. }
  755. /**
  756. * 设置数据
  757. * @access public
  758. * @param mixed $field 字段名或者数据
  759. * @param mixed $value 字段值
  760. * @return $this
  761. */
  762. public function data($field, $value = null)
  763. {
  764. if (is_array($field)) {
  765. $this->options['data'] = isset($this->options['data']) ? array_merge($this->options['data'], $field) : $field;
  766. } else {
  767. $this->options['data'][$field] = $value;
  768. }
  769. return $this;
  770. }
  771. /**
  772. * 字段值增长
  773. * @access public
  774. * @param string|array $field 字段名
  775. * @param integer $step 增长值
  776. * @return $this
  777. */
  778. public function inc($field, $step = 1)
  779. {
  780. $fields = is_string($field) ? explode(',', $field) : $field;
  781. foreach ($fields as $field) {
  782. $this->data($field, ['inc', $field, $step]);
  783. }
  784. return $this;
  785. }
  786. /**
  787. * 字段值减少
  788. * @access public
  789. * @param string|array $field 字段名
  790. * @param integer $step 增长值
  791. * @return $this
  792. */
  793. public function dec($field, $step = 1)
  794. {
  795. $fields = is_string($field) ? explode(',', $field) : $field;
  796. foreach ($fields as $field) {
  797. $this->data($field, ['dec', $field, $step]);
  798. }
  799. return $this;
  800. }
  801. /**
  802. * 使用表达式设置数据
  803. * @access public
  804. * @param string $field 字段名
  805. * @param string $value 字段值
  806. * @return $this
  807. */
  808. public function exp($field, $value)
  809. {
  810. $this->data($field, ['exp', $value]);
  811. return $this;
  812. }
  813. /**
  814. * 指定JOIN查询字段
  815. * @access public
  816. * @param string|array $table 数据表
  817. * @param string|array $field 查询字段
  818. * @param string|array $on JOIN条件
  819. * @param string $type JOIN类型
  820. * @return $this
  821. */
  822. public function view($join, $field = true, $on = null, $type = 'INNER')
  823. {
  824. $this->options['view'] = true;
  825. if (is_array($join) && key($join) !== 0) {
  826. foreach ($join as $key => $val) {
  827. $this->view($key, $val[0], isset($val[1]) ? $val[1] : null, isset($val[2]) ? $val[2] : 'INNER');
  828. }
  829. } else {
  830. $fields = [];
  831. $table = $this->getJoinTable($join, $alias);
  832. if (true === $field) {
  833. $fields = $alias . '.*';
  834. } else {
  835. if (is_string($field)) {
  836. $field = explode(',', $field);
  837. }
  838. foreach ($field as $key => $val) {
  839. if (is_numeric($key)) {
  840. $fields[] = $alias . '.' . $val;
  841. $this->options['map'][$val] = $alias . '.' . $val;
  842. } else {
  843. if (preg_match('/[,=\.\'\"\(\s]/', $key)) {
  844. $name = $key;
  845. } else {
  846. $name = $alias . '.' . $key;
  847. }
  848. $fields[$name] = $val;
  849. $this->options['map'][$val] = $name;
  850. }
  851. }
  852. }
  853. $this->field($fields);
  854. if ($on) {
  855. $this->join($table, $on, $type);
  856. } else {
  857. $this->table($table);
  858. }
  859. }
  860. return $this;
  861. }
  862. /**
  863. * 设置分表规则
  864. * @access public
  865. * @param array $data 操作的数据
  866. * @param string $field 分表依据的字段
  867. * @param array $rule 分表规则
  868. * @return $this
  869. */
  870. public function partition($data, $field, $rule = [])
  871. {
  872. $this->options['table'] = $this->getPartitionTableName($data, $field, $rule);
  873. return $this;
  874. }
  875. /**
  876. * 指定AND查询条件
  877. * @access public
  878. * @param mixed $field 查询字段
  879. * @param mixed $op 查询表达式
  880. * @param mixed $condition 查询条件
  881. * @return $this
  882. */
  883. public function where($field, $op = null, $condition = null)
  884. {
  885. $param = func_get_args();
  886. array_shift($param);
  887. $this->parseWhereExp('AND', $field, $op, $condition, $param);
  888. return $this;
  889. }
  890. /**
  891. * 指定OR查询条件
  892. * @access public
  893. * @param mixed $field 查询字段
  894. * @param mixed $op 查询表达式
  895. * @param mixed $condition 查询条件
  896. * @return $this
  897. */
  898. public function whereOr($field, $op = null, $condition = null)
  899. {
  900. $param = func_get_args();
  901. array_shift($param);
  902. $this->parseWhereExp('OR', $field, $op, $condition, $param);
  903. return $this;
  904. }
  905. /**
  906. * 指定XOR查询条件
  907. * @access public
  908. * @param mixed $field 查询字段
  909. * @param mixed $op 查询表达式
  910. * @param mixed $condition 查询条件
  911. * @return $this
  912. */
  913. public function whereXor($field, $op = null, $condition = null)
  914. {
  915. $param = func_get_args();
  916. array_shift($param);
  917. $this->parseWhereExp('XOR', $field, $op, $condition, $param);
  918. return $this;
  919. }
  920. /**
  921. * 指定Null查询条件
  922. * @access public
  923. * @param mixed $field 查询字段
  924. * @param string $logic 查询逻辑 and or xor
  925. * @return $this
  926. */
  927. public function whereNull($field, $logic = 'AND')
  928. {
  929. $this->parseWhereExp($logic, $field, 'null', null);
  930. return $this;
  931. }
  932. /**
  933. * 指定NotNull查询条件
  934. * @access public
  935. * @param mixed $field 查询字段
  936. * @param string $logic 查询逻辑 and or xor
  937. * @return $this
  938. */
  939. public function whereNotNull($field, $logic = 'AND')
  940. {
  941. $this->parseWhereExp($logic, $field, 'notnull', null);
  942. return $this;
  943. }
  944. /**
  945. * 指定Exists查询条件
  946. * @access public
  947. * @param mixed $condition 查询条件
  948. * @param string $logic 查询逻辑 and or xor
  949. * @return $this
  950. */
  951. public function whereExists($condition, $logic = 'AND')
  952. {
  953. $this->options['where'][strtoupper($logic)][] = ['exists', $condition];
  954. return $this;
  955. }
  956. /**
  957. * 指定NotExists查询条件
  958. * @access public
  959. * @param mixed $condition 查询条件
  960. * @param string $logic 查询逻辑 and or xor
  961. * @return $this
  962. */
  963. public function whereNotExists($condition, $logic = 'AND')
  964. {
  965. $this->options['where'][strtoupper($logic)][] = ['not exists', $condition];
  966. return $this;
  967. }
  968. /**
  969. * 指定In查询条件
  970. * @access public
  971. * @param mixed $field 查询字段
  972. * @param mixed $condition 查询条件
  973. * @param string $logic 查询逻辑 and or xor
  974. * @return $this
  975. */
  976. public function whereIn($field, $condition, $logic = 'AND')
  977. {
  978. $this->parseWhereExp($logic, $field, 'in', $condition);
  979. return $this;
  980. }
  981. /**
  982. * 指定NotIn查询条件
  983. * @access public
  984. * @param mixed $field 查询字段
  985. * @param mixed $condition 查询条件
  986. * @param string $logic 查询逻辑 and or xor
  987. * @return $this
  988. */
  989. public function whereNotIn($field, $condition, $logic = 'AND')
  990. {
  991. $this->parseWhereExp($logic, $field, 'not in', $condition);
  992. return $this;
  993. }
  994. /**
  995. * 指定Like查询条件
  996. * @access public
  997. * @param mixed $field 查询字段
  998. * @param mixed $condition 查询条件
  999. * @param string $logic 查询逻辑 and or xor
  1000. * @return $this
  1001. */
  1002. public function whereLike($field, $condition, $logic = 'AND')
  1003. {
  1004. $this->parseWhereExp($logic, $field, 'like', $condition);
  1005. return $this;
  1006. }
  1007. /**
  1008. * 指定NotLike查询条件
  1009. * @access public
  1010. * @param mixed $field 查询字段
  1011. * @param mixed $condition 查询条件
  1012. * @param string $logic 查询逻辑 and or xor
  1013. * @return $this
  1014. */
  1015. public function whereNotLike($field, $condition, $logic = 'AND')
  1016. {
  1017. $this->parseWhereExp($logic, $field, 'not like', $condition);
  1018. return $this;
  1019. }
  1020. /**
  1021. * 指定Between查询条件
  1022. * @access public
  1023. * @param mixed $field 查询字段
  1024. * @param mixed $condition 查询条件
  1025. * @param string $logic 查询逻辑 and or xor
  1026. * @return $this
  1027. */
  1028. public function whereBetween($field, $condition, $logic = 'AND')
  1029. {
  1030. $this->parseWhereExp($logic, $field, 'between', $condition);
  1031. return $this;
  1032. }
  1033. /**
  1034. * 指定NotBetween查询条件
  1035. * @access public
  1036. * @param mixed $field 查询字段
  1037. * @param mixed $condition 查询条件
  1038. * @param string $logic 查询逻辑 and or xor
  1039. * @return $this
  1040. */
  1041. public function whereNotBetween($field, $condition, $logic = 'AND')
  1042. {
  1043. $this->parseWhereExp($logic, $field, 'not between', $condition);
  1044. return $this;
  1045. }
  1046. /**
  1047. * 指定Exp查询条件
  1048. * @access public
  1049. * @param mixed $field 查询字段
  1050. * @param mixed $condition 查询条件
  1051. * @param string $logic 查询逻辑 and or xor
  1052. * @return $this
  1053. */
  1054. public function whereExp($field, $condition, $logic = 'AND')
  1055. {
  1056. $this->parseWhereExp($logic, $field, 'exp', $condition);
  1057. return $this;
  1058. }
  1059. /**
  1060. * 设置软删除字段及条件
  1061. * @access public
  1062. * @param false|string $field 查询字段
  1063. * @param mixed $condition 查询条件
  1064. * @return $this
  1065. */
  1066. public function useSoftDelete($field, $condition = null)
  1067. {
  1068. if ($field) {
  1069. $this->options['soft_delete'] = [$field, $condition ?: ['null', '']];
  1070. }
  1071. return $this;
  1072. }
  1073. /**
  1074. * 分析查询表达式
  1075. * @access public
  1076. * @param string $logic 查询逻辑 and or xor
  1077. * @param string|array|\Closure $field 查询字段
  1078. * @param mixed $op 查询表达式
  1079. * @param mixed $condition 查询条件
  1080. * @param array $param 查询参数
  1081. * @return void
  1082. */
  1083. protected function parseWhereExp($logic, $field, $op, $condition, $param = [])
  1084. {
  1085. $logic = strtoupper($logic);
  1086. if ($field instanceof \Closure) {
  1087. $this->options['where'][$logic][] = is_string($op) ? [$op, $field] : $field;
  1088. return;
  1089. }
  1090. if (is_string($field) && !empty($this->options['via']) && !strpos($field, '.')) {
  1091. $field = $this->options['via'] . '.' . $field;
  1092. }
  1093. if (is_string($field) && preg_match('/[,=\>\<\'\"\(\s]/', $field)) {
  1094. $where[] = ['exp', $field];
  1095. if (is_array($op)) {
  1096. // 参数绑定
  1097. $this->bind($op);
  1098. }
  1099. } elseif (is_null($op) && is_null($condition)) {
  1100. if (is_array($field)) {
  1101. // 数组批量查询
  1102. $where = $field;
  1103. foreach ($where as $k => $val) {
  1104. $this->options['multi'][$logic][$k][] = $val;
  1105. }
  1106. } elseif ($field && is_string($field)) {
  1107. // 字符串查询
  1108. $where[$field] = ['null', ''];
  1109. $this->options['multi'][$logic][$field][] = $where[$field];
  1110. }
  1111. } elseif (is_array($op)) {
  1112. $where[$field] = $param;
  1113. } elseif (in_array(strtolower($op), ['null', 'notnull', 'not null'])) {
  1114. // null查询
  1115. $where[$field] = [$op, ''];
  1116. $this->options['multi'][$logic][$field][] = $where[$field];
  1117. } elseif (is_null($condition)) {
  1118. // 字段相等查询
  1119. $where[$field] = ['eq', $op];
  1120. $this->options['multi'][$logic][$field][] = $where[$field];
  1121. } else {
  1122. $where[$field] = [$op, $condition, isset($param[2]) ? $param[2] : null];
  1123. if ('exp' == strtolower($op) && isset($param[2]) && is_array($param[2])) {
  1124. // 参数绑定
  1125. $this->bind($param[2]);
  1126. }
  1127. // 记录一个字段多次查询条件
  1128. $this->options['multi'][$logic][$field][] = $where[$field];
  1129. }
  1130. if (!empty($where)) {
  1131. if (!isset($this->options['where'][$logic])) {
  1132. $this->options['where'][$logic] = [];
  1133. }
  1134. if (is_string($field) && $this->checkMultiField($field, $logic)) {
  1135. $where[$field] = $this->options['multi'][$logic][$field];
  1136. } elseif (is_array($field)) {
  1137. foreach ($field as $key => $val) {
  1138. if ($this->checkMultiField($key, $logic)) {
  1139. $where[$key] = $this->options['multi'][$logic][$key];
  1140. }
  1141. }
  1142. }
  1143. $this->options['where'][$logic] = array_merge($this->options['where'][$logic], $where);
  1144. }
  1145. }
  1146. /**
  1147. * 检查是否存在一个字段多次查询条件
  1148. * @access public
  1149. * @param string $field 查询字段
  1150. * @param string $logic 查询逻辑 and or xor
  1151. * @return bool
  1152. */
  1153. private function checkMultiField($field, $logic)
  1154. {
  1155. return isset($this->options['multi'][$logic][$field]) && count($this->options['multi'][$logic][$field]) > 1;
  1156. }
  1157. /**
  1158. * 去除某个查询条件
  1159. * @access public
  1160. * @param string $field 查询字段
  1161. * @param string $logic 查询逻辑 and or xor
  1162. * @return $this
  1163. */
  1164. public function removeWhereField($field, $logic = 'AND')
  1165. {
  1166. $logic = strtoupper($logic);
  1167. if (isset($this->options['where'][$logic][$field])) {
  1168. unset($this->options['where'][$logic][$field]);
  1169. unset($this->options['multi'][$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 (!App::$debug && 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. /** @var Model $class */
  1787. $class = $this->model;
  1788. foreach ($with as $key => $relation) {
  1789. $subRelation = '';
  1790. $closure = false;
  1791. if ($relation instanceof \Closure) {
  1792. // 支持闭包查询过滤关联条件
  1793. $closure = $relation;
  1794. $relation = $key;
  1795. $with[$key] = $key;
  1796. } elseif (is_array($relation)) {
  1797. $subRelation = $relation;
  1798. $relation = $key;
  1799. } elseif (is_string($relation) && strpos($relation, '.')) {
  1800. $with[$key] = $relation;
  1801. list($relation, $subRelation) = explode('.', $relation, 2);
  1802. }
  1803. /** @var Relation $model */
  1804. $relation = Loader::parseName($relation, 1, false);
  1805. $model = $class->$relation();
  1806. if ($model instanceof OneToOne && 0 == $model->getEagerlyType()) {
  1807. $model->eagerly($this, $relation, $subRelation, $closure, $first);
  1808. $first = false;
  1809. } elseif ($closure) {
  1810. $with[$key] = $closure;
  1811. }
  1812. }
  1813. $this->via();
  1814. if (isset($this->options['with'])) {
  1815. $this->options['with'] = array_merge($this->options['with'], $with);
  1816. } else {
  1817. $this->options['with'] = $with;
  1818. }
  1819. return $this;
  1820. }
  1821. /**
  1822. * 关联统计
  1823. * @access public
  1824. * @param string|array $relation 关联方法名
  1825. * @param bool $subQuery 是否使用子查询
  1826. * @return $this
  1827. */
  1828. public function withCount($relation, $subQuery = true)
  1829. {
  1830. if (!$subQuery) {
  1831. $this->options['with_count'] = $relation;
  1832. } else {
  1833. $relations = is_string($relation) ? explode(',', $relation) : $relation;
  1834. if (!isset($this->options['field'])) {
  1835. $this->field('*');
  1836. }
  1837. foreach ($relations as $key => $relation) {
  1838. $closure = false;
  1839. if ($relation instanceof \Closure) {
  1840. $closure = $relation;
  1841. $relation = $key;
  1842. }
  1843. $relation = Loader::parseName($relation, 1, false);
  1844. $count = '(' . $this->model->$relation()->getRelationCountQuery($closure) . ')';
  1845. $this->field([$count => Loader::parseName($relation) . '_count']);
  1846. }
  1847. }
  1848. return $this;
  1849. }
  1850. /**
  1851. * 关联预加载中 获取关联指定字段值
  1852. * example:
  1853. * Model::with(['relation' => function($query){
  1854. * $query->withField("id,name");
  1855. * }])
  1856. *
  1857. * @param string | array $field 指定获取的字段
  1858. * @return $this
  1859. */
  1860. public function withField($field)
  1861. {
  1862. $this->options['with_field'] = $field;
  1863. return $this;
  1864. }
  1865. /**
  1866. * 设置当前字段添加的表别名
  1867. * @access public
  1868. * @param string $via
  1869. * @return $this
  1870. */
  1871. public function via($via = '')
  1872. {
  1873. $this->options['via'] = $via;
  1874. return $this;
  1875. }
  1876. /**
  1877. * 设置关联查询
  1878. * @access public
  1879. * @param string|array $relation 关联名称
  1880. * @return $this
  1881. */
  1882. public function relation($relation)
  1883. {
  1884. if (empty($relation)) {
  1885. return $this;
  1886. }
  1887. if (is_string($relation)) {
  1888. $relation = explode(',', $relation);
  1889. }
  1890. if (isset($this->options['relation'])) {
  1891. $this->options['relation'] = array_merge($this->options['relation'], $relation);
  1892. } else {
  1893. $this->options['relation'] = $relation;
  1894. }
  1895. return $this;
  1896. }
  1897. /**
  1898. * 把主键值转换为查询条件 支持复合主键
  1899. * @access public
  1900. * @param array|string $data 主键数据
  1901. * @param mixed $options 表达式参数
  1902. * @return void
  1903. * @throws Exception
  1904. */
  1905. protected function parsePkWhere($data, &$options)
  1906. {
  1907. $pk = $this->getPk($options);
  1908. // 获取当前数据表
  1909. $table = is_array($options['table']) ? key($options['table']) : $options['table'];
  1910. if (!empty($options['alias'][$table])) {
  1911. $alias = $options['alias'][$table];
  1912. }
  1913. if (is_string($pk)) {
  1914. $key = isset($alias) ? $alias . '.' . $pk : $pk;
  1915. // 根据主键查询
  1916. if (is_array($data)) {
  1917. $where[$key] = isset($data[$pk]) ? $data[$pk] : ['in', $data];
  1918. } else {
  1919. $where[$key] = strpos($data, ',') ? ['IN', $data] : $data;
  1920. }
  1921. } elseif (is_array($pk) && is_array($data) && !empty($data)) {
  1922. // 根据复合主键查询
  1923. foreach ($pk as $key) {
  1924. if (isset($data[$key])) {
  1925. $attr = isset($alias) ? $alias . '.' . $key : $key;
  1926. $where[$attr] = $data[$key];
  1927. } else {
  1928. throw new Exception('miss complex primary data');
  1929. }
  1930. }
  1931. }
  1932. if (!empty($where)) {
  1933. if (isset($options['where']['AND'])) {
  1934. $options['where']['AND'] = array_merge($options['where']['AND'], $where);
  1935. } else {
  1936. $options['where']['AND'] = $where;
  1937. }
  1938. }
  1939. return;
  1940. }
  1941. /**
  1942. * 插入记录
  1943. * @access public
  1944. * @param mixed $data 数据
  1945. * @param boolean $replace 是否replace
  1946. * @param boolean $getLastInsID 返回自增主键
  1947. * @param string $sequence 自增序列名
  1948. * @return integer|string
  1949. */
  1950. public function insert(array $data = [], $replace = false, $getLastInsID = false, $sequence = null)
  1951. {
  1952. // 分析查询表达式
  1953. $options = $this->parseExpress();
  1954. $data = array_merge($options['data'], $data);
  1955. // 生成SQL语句
  1956. $sql = $this->builder->insert($data, $options, $replace);
  1957. // 获取参数绑定
  1958. $bind = $this->getBind();
  1959. if ($options['fetch_sql']) {
  1960. // 获取实际执行的SQL语句
  1961. return $this->connection->getRealSql($sql, $bind);
  1962. }
  1963. // 执行操作
  1964. $result = 0 === $sql ? 0 : $this->execute($sql, $bind);
  1965. if ($result) {
  1966. $sequence = $sequence ?: (isset($options['sequence']) ? $options['sequence'] : null);
  1967. $lastInsId = $this->getLastInsID($sequence);
  1968. if ($lastInsId) {
  1969. $pk = $this->getPk($options);
  1970. if (is_string($pk)) {
  1971. $data[$pk] = $lastInsId;
  1972. }
  1973. }
  1974. $options['data'] = $data;
  1975. $this->trigger('after_insert', $options);
  1976. if ($getLastInsID) {
  1977. return $lastInsId;
  1978. }
  1979. }
  1980. return $result;
  1981. }
  1982. /**
  1983. * 插入记录并获取自增ID
  1984. * @access public
  1985. * @param mixed $data 数据
  1986. * @param boolean $replace 是否replace
  1987. * @param string $sequence 自增序列名
  1988. * @return integer|string
  1989. */
  1990. public function insertGetId(array $data, $replace = false, $sequence = null)
  1991. {
  1992. return $this->insert($data, $replace, true, $sequence);
  1993. }
  1994. /**
  1995. * 批量插入记录
  1996. * @access public
  1997. * @param mixed $dataSet 数据集
  1998. * @param boolean $replace 是否replace
  1999. * @param integer $limit 每次写入数据限制
  2000. * @return integer|string
  2001. */
  2002. public function insertAll(array $dataSet, $replace = false, $limit = null)
  2003. {
  2004. // 分析查询表达式
  2005. $options = $this->parseExpress();
  2006. if (!is_array(reset($dataSet))) {
  2007. return false;
  2008. }
  2009. // 生成SQL语句
  2010. if (is_null($limit)) {
  2011. $sql = $this->builder->insertAll($dataSet, $options, $replace);
  2012. } else {
  2013. $array = array_chunk($dataSet, $limit, true);
  2014. foreach ($array as $item) {
  2015. $sql[] = $this->builder->insertAll($item, $options, $replace);
  2016. }
  2017. }
  2018. // 获取参数绑定
  2019. $bind = $this->getBind();
  2020. if ($options['fetch_sql']) {
  2021. // 获取实际执行的SQL语句
  2022. return $this->connection->getRealSql($sql, $bind);
  2023. } elseif (is_array($sql)) {
  2024. // 执行操作
  2025. return $this->batchQuery($sql, $bind);
  2026. } else {
  2027. // 执行操作
  2028. return $this->execute($sql, $bind);
  2029. }
  2030. }
  2031. /**
  2032. * 通过Select方式插入记录
  2033. * @access public
  2034. * @param string $fields 要插入的数据表字段名
  2035. * @param string $table 要插入的数据表名
  2036. * @return integer|string
  2037. * @throws PDOException
  2038. */
  2039. public function selectInsert($fields, $table)
  2040. {
  2041. // 分析查询表达式
  2042. $options = $this->parseExpress();
  2043. // 生成SQL语句
  2044. $table = $this->parseSqlTable($table);
  2045. $sql = $this->builder->selectInsert($fields, $table, $options);
  2046. // 获取参数绑定
  2047. $bind = $this->getBind();
  2048. if ($options['fetch_sql']) {
  2049. // 获取实际执行的SQL语句
  2050. return $this->connection->getRealSql($sql, $bind);
  2051. } else {
  2052. // 执行操作
  2053. return $this->execute($sql, $bind);
  2054. }
  2055. }
  2056. /**
  2057. * 更新记录
  2058. * @access public
  2059. * @param mixed $data 数据
  2060. * @return integer|string
  2061. * @throws Exception
  2062. * @throws PDOException
  2063. */
  2064. public function update(array $data = [])
  2065. {
  2066. $options = $this->parseExpress();
  2067. $data = array_merge($options['data'], $data);
  2068. $pk = $this->getPk($options);
  2069. if (isset($options['cache']) && is_string($options['cache']['key'])) {
  2070. $key = $options['cache']['key'];
  2071. }
  2072. if (empty($options['where'])) {
  2073. // 如果存在主键数据 则自动作为更新条件
  2074. if (is_string($pk) && isset($data[$pk])) {
  2075. $where[$pk] = $data[$pk];
  2076. if (!isset($key)) {
  2077. $key = 'think:' . $options['table'] . '|' . $data[$pk];
  2078. }
  2079. unset($data[$pk]);
  2080. } elseif (is_array($pk)) {
  2081. // 增加复合主键支持
  2082. foreach ($pk as $field) {
  2083. if (isset($data[$field])) {
  2084. $where[$field] = $data[$field];
  2085. } else {
  2086. // 如果缺少复合主键数据则不执行
  2087. throw new Exception('miss complex primary data');
  2088. }
  2089. unset($data[$field]);
  2090. }
  2091. }
  2092. if (!isset($where)) {
  2093. // 如果没有任何更新条件则不执行
  2094. throw new Exception('miss update condition');
  2095. } else {
  2096. $options['where']['AND'] = $where;
  2097. }
  2098. } elseif (!isset($key) && is_string($pk) && isset($options['where']['AND'][$pk])) {
  2099. $key = $this->getCacheKey($options['where']['AND'][$pk], $options, $this->bind);
  2100. }
  2101. // 生成UPDATE SQL语句
  2102. $sql = $this->builder->update($data, $options);
  2103. // 获取参数绑定
  2104. $bind = $this->getBind();
  2105. if ($options['fetch_sql']) {
  2106. // 获取实际执行的SQL语句
  2107. return $this->connection->getRealSql($sql, $bind);
  2108. } else {
  2109. // 检测缓存
  2110. if (isset($key) && Cache::get($key)) {
  2111. // 删除缓存
  2112. Cache::rm($key);
  2113. } elseif (!empty($options['cache']['tag'])) {
  2114. Cache::clear($options['cache']['tag']);
  2115. }
  2116. // 执行操作
  2117. $result = '' == $sql ? 0 : $this->execute($sql, $bind);
  2118. if ($result) {
  2119. if (is_string($pk) && isset($where[$pk])) {
  2120. $data[$pk] = $where[$pk];
  2121. } elseif (is_string($pk) && isset($key) && strpos($key, '|')) {
  2122. list($a, $val) = explode('|', $key);
  2123. $data[$pk] = $val;
  2124. }
  2125. $options['data'] = $data;
  2126. $this->trigger('after_update', $options);
  2127. }
  2128. return $result;
  2129. }
  2130. }
  2131. /**
  2132. * 执行查询但只返回PDOStatement对象
  2133. * @access public
  2134. * @return \PDOStatement|string
  2135. */
  2136. public function getPdo()
  2137. {
  2138. // 分析查询表达式
  2139. $options = $this->parseExpress();
  2140. // 生成查询SQL
  2141. $sql = $this->builder->select($options);
  2142. // 获取参数绑定
  2143. $bind = $this->getBind();
  2144. if ($options['fetch_sql']) {
  2145. // 获取实际执行的SQL语句
  2146. return $this->connection->getRealSql($sql, $bind);
  2147. }
  2148. // 执行查询操作
  2149. return $this->query($sql, $bind, $options['master'], true);
  2150. }
  2151. /**
  2152. * 查找记录
  2153. * @access public
  2154. * @param array|string|Query|\Closure $data
  2155. * @return Collection|false|\PDOStatement|string
  2156. * @throws DbException
  2157. * @throws ModelNotFoundException
  2158. * @throws DataNotFoundException
  2159. */
  2160. public function select($data = null)
  2161. {
  2162. if ($data instanceof Query) {
  2163. return $data->select();
  2164. } elseif ($data instanceof \Closure) {
  2165. call_user_func_array($data, [ & $this]);
  2166. $data = null;
  2167. }
  2168. // 分析查询表达式
  2169. $options = $this->parseExpress();
  2170. if (false === $data) {
  2171. // 用于子查询 不查询只返回SQL
  2172. $options['fetch_sql'] = true;
  2173. } elseif (!is_null($data)) {
  2174. // 主键条件分析
  2175. $this->parsePkWhere($data, $options);
  2176. }
  2177. $resultSet = false;
  2178. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  2179. // 判断查询缓存
  2180. $cache = $options['cache'];
  2181. unset($options['cache']);
  2182. $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options) . serialize($this->bind));
  2183. $resultSet = Cache::get($key);
  2184. }
  2185. if (false === $resultSet) {
  2186. // 生成查询SQL
  2187. $sql = $this->builder->select($options);
  2188. // 获取参数绑定
  2189. $bind = $this->getBind();
  2190. if ($options['fetch_sql']) {
  2191. // 获取实际执行的SQL语句
  2192. return $this->connection->getRealSql($sql, $bind);
  2193. }
  2194. $options['data'] = $data;
  2195. if ($resultSet = $this->trigger('before_select', $options)) {
  2196. } else {
  2197. // 执行查询操作
  2198. $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']);
  2199. if ($resultSet instanceof \PDOStatement) {
  2200. // 返回PDOStatement对象
  2201. return $resultSet;
  2202. }
  2203. }
  2204. if (isset($cache) && false !== $resultSet) {
  2205. // 缓存数据集
  2206. $this->cacheData($key, $resultSet, $cache);
  2207. }
  2208. }
  2209. // 数据列表读取后的处理
  2210. if (!empty($this->model)) {
  2211. // 生成模型对象
  2212. if (count($resultSet) > 0) {
  2213. foreach ($resultSet as $key => $result) {
  2214. /** @var Model $model */
  2215. $model = $this->model->newInstance($result);
  2216. $model->isUpdate(true);
  2217. // 关联查询
  2218. if (!empty($options['relation'])) {
  2219. $model->relationQuery($options['relation']);
  2220. }
  2221. // 关联统计
  2222. if (!empty($options['with_count'])) {
  2223. $model->relationCount($model, $options['with_count']);
  2224. }
  2225. $resultSet[$key] = $model;
  2226. }
  2227. if (!empty($options['with'])) {
  2228. // 预载入
  2229. $model->eagerlyResultSet($resultSet, $options['with']);
  2230. }
  2231. // 模型数据集转换
  2232. $resultSet = $model->toCollection($resultSet);
  2233. } else {
  2234. $resultSet = $this->model->toCollection($resultSet);
  2235. }
  2236. } elseif ('collection' == $this->connection->getConfig('resultset_type')) {
  2237. // 返回Collection对象
  2238. $resultSet = new Collection($resultSet);
  2239. }
  2240. // 返回结果处理
  2241. if (!empty($options['fail']) && count($resultSet) == 0) {
  2242. $this->throwNotFound($options);
  2243. }
  2244. return $resultSet;
  2245. }
  2246. /**
  2247. * 缓存数据
  2248. * @access public
  2249. * @param string $key 缓存标识
  2250. * @param mixed $data 缓存数据
  2251. * @param array $config 缓存参数
  2252. */
  2253. protected function cacheData($key, $data, $config = [])
  2254. {
  2255. if (isset($config['tag'])) {
  2256. Cache::tag($config['tag'])->set($key, $data, $config['expire']);
  2257. } else {
  2258. Cache::set($key, $data, $config['expire']);
  2259. }
  2260. }
  2261. /**
  2262. * 生成缓存标识
  2263. * @access public
  2264. * @param mixed $value 缓存数据
  2265. * @param array $options 缓存参数
  2266. * @param array $bind 绑定参数
  2267. * @return string
  2268. */
  2269. protected function getCacheKey($value, $options, $bind = [])
  2270. {
  2271. if (is_scalar($value)) {
  2272. $data = $value;
  2273. } elseif (is_array($value) && is_string($value[0]) && 'eq' == strtolower($value[0])) {
  2274. $data = $value[1];
  2275. }
  2276. if (isset($data)) {
  2277. return 'think:' . (is_array($options['table']) ? key($options['table']) : $options['table']) . '|' . $data;
  2278. } else {
  2279. return md5(serialize($options) . serialize($bind));
  2280. }
  2281. }
  2282. /**
  2283. * 查找单条记录
  2284. * @access public
  2285. * @param array|string|Query|\Closure $data
  2286. * @return array|false|\PDOStatement|string|Model
  2287. * @throws DbException
  2288. * @throws ModelNotFoundException
  2289. * @throws DataNotFoundException
  2290. */
  2291. public function find($data = null)
  2292. {
  2293. if ($data instanceof Query) {
  2294. return $data->find();
  2295. } elseif ($data instanceof \Closure) {
  2296. call_user_func_array($data, [ & $this]);
  2297. $data = null;
  2298. }
  2299. // 分析查询表达式
  2300. $options = $this->parseExpress();
  2301. $pk = $this->getPk($options);
  2302. if (!is_null($data)) {
  2303. // AR模式分析主键条件
  2304. $this->parsePkWhere($data, $options);
  2305. } elseif (!empty($options['cache']) && true === $options['cache']['key'] && is_string($pk) && isset($options['where']['AND'][$pk])) {
  2306. $key = $this->getCacheKey($options['where']['AND'][$pk], $options, $this->bind);
  2307. }
  2308. $options['limit'] = 1;
  2309. $result = false;
  2310. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  2311. // 判断查询缓存
  2312. $cache = $options['cache'];
  2313. if (true === $cache['key'] && !is_null($data) && !is_array($data)) {
  2314. $key = 'think:' . (is_array($options['table']) ? key($options['table']) : $options['table']) . '|' . $data;
  2315. } elseif (is_string($cache['key'])) {
  2316. $key = $cache['key'];
  2317. } elseif (!isset($key)) {
  2318. $key = md5(serialize($options) . serialize($this->bind));
  2319. }
  2320. $result = Cache::get($key);
  2321. }
  2322. if (false === $result) {
  2323. // 生成查询SQL
  2324. $sql = $this->builder->select($options);
  2325. // 获取参数绑定
  2326. $bind = $this->getBind();
  2327. if ($options['fetch_sql']) {
  2328. // 获取实际执行的SQL语句
  2329. return $this->connection->getRealSql($sql, $bind);
  2330. }
  2331. if (is_string($pk)) {
  2332. if (!is_array($data)) {
  2333. if (isset($key) && strpos($key, '|')) {
  2334. list($a, $val) = explode('|', $key);
  2335. $item[$pk] = $val;
  2336. } else {
  2337. $item[$pk] = $data;
  2338. }
  2339. $data = $item;
  2340. }
  2341. }
  2342. $options['data'] = $data;
  2343. // 事件回调
  2344. if ($result = $this->trigger('before_find', $options)) {
  2345. } else {
  2346. // 执行查询
  2347. $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']);
  2348. if ($resultSet instanceof \PDOStatement) {
  2349. // 返回PDOStatement对象
  2350. return $resultSet;
  2351. }
  2352. $result = isset($resultSet[0]) ? $resultSet[0] : null;
  2353. }
  2354. if (isset($cache) && $result) {
  2355. // 缓存数据
  2356. $this->cacheData($key, $result, $cache);
  2357. }
  2358. }
  2359. // 数据处理
  2360. if (!empty($result)) {
  2361. if (!empty($this->model)) {
  2362. // 返回模型对象
  2363. $result = $this->model->newInstance($result);
  2364. $result->isUpdate(true, isset($options['where']['AND']) ? $options['where']['AND'] : null);
  2365. // 关联查询
  2366. if (!empty($options['relation'])) {
  2367. $result->relationQuery($options['relation']);
  2368. }
  2369. // 预载入查询
  2370. if (!empty($options['with'])) {
  2371. $result->eagerlyResult($result, $options['with']);
  2372. }
  2373. // 关联统计
  2374. if (!empty($options['with_count'])) {
  2375. $result->relationCount($result, $options['with_count']);
  2376. }
  2377. }
  2378. } elseif (!empty($options['fail'])) {
  2379. $this->throwNotFound($options);
  2380. }
  2381. return $result;
  2382. }
  2383. /**
  2384. * 查询失败 抛出异常
  2385. * @access public
  2386. * @param array $options 查询参数
  2387. * @throws ModelNotFoundException
  2388. * @throws DataNotFoundException
  2389. */
  2390. protected function throwNotFound($options = [])
  2391. {
  2392. if (!empty($this->model)) {
  2393. $class = get_class($this->model);
  2394. throw new ModelNotFoundException('model data Not Found:' . $class, $class, $options);
  2395. } else {
  2396. $table = is_array($options['table']) ? key($options['table']) : $options['table'];
  2397. throw new DataNotFoundException('table data not Found:' . $table, $table, $options);
  2398. }
  2399. }
  2400. /**
  2401. * 查找多条记录 如果不存在则抛出异常
  2402. * @access public
  2403. * @param array|string|Query|\Closure $data
  2404. * @return array|\PDOStatement|string|Model
  2405. * @throws DbException
  2406. * @throws ModelNotFoundException
  2407. * @throws DataNotFoundException
  2408. */
  2409. public function selectOrFail($data = null)
  2410. {
  2411. return $this->failException(true)->select($data);
  2412. }
  2413. /**
  2414. * 查找单条记录 如果不存在则抛出异常
  2415. * @access public
  2416. * @param array|string|Query|\Closure $data
  2417. * @return array|\PDOStatement|string|Model
  2418. * @throws DbException
  2419. * @throws ModelNotFoundException
  2420. * @throws DataNotFoundException
  2421. */
  2422. public function findOrFail($data = null)
  2423. {
  2424. return $this->failException(true)->find($data);
  2425. }
  2426. /**
  2427. * 分批数据返回处理
  2428. * @access public
  2429. * @param integer $count 每次处理的数据数量
  2430. * @param callable $callback 处理回调方法
  2431. * @param string $column 分批处理的字段名
  2432. * @param string $order 排序规则
  2433. * @return boolean
  2434. * @throws \LogicException
  2435. */
  2436. public function chunk($count, $callback, $column = null, $order = 'asc')
  2437. {
  2438. $options = $this->getOptions();
  2439. if (empty($options['table'])) {
  2440. $options['table'] = $this->getTable();
  2441. }
  2442. $column = $column ?: $this->getPk($options);
  2443. if (isset($options['order'])) {
  2444. if (App::$debug) {
  2445. throw new \LogicException('chunk not support call order');
  2446. }
  2447. unset($options['order']);
  2448. }
  2449. $bind = $this->bind;
  2450. if (is_array($column)) {
  2451. $times = 1;
  2452. $query = $this->options($options)->page($times, $count);
  2453. } else {
  2454. if (strpos($column, '.')) {
  2455. list($alias, $key) = explode('.', $column);
  2456. } else {
  2457. $key = $column;
  2458. }
  2459. $query = $this->options($options)->limit($count);
  2460. }
  2461. $resultSet = $query->order($column, $order)->select();
  2462. while (count($resultSet) > 0) {
  2463. if ($resultSet instanceof Collection) {
  2464. $resultSet = $resultSet->all();
  2465. }
  2466. if (false === call_user_func($callback, $resultSet)) {
  2467. return false;
  2468. }
  2469. if (is_array($column)) {
  2470. $times++;
  2471. $query = $this->options($options)->page($times, $count);
  2472. } else {
  2473. $end = end($resultSet);
  2474. $lastId = is_array($end) ? $end[$key] : $end->getData($key);
  2475. $query = $this->options($options)
  2476. ->limit($count)
  2477. ->where($column, 'asc' == strtolower($order) ? '>' : '<', $lastId);
  2478. }
  2479. $resultSet = $query->bind($bind)->order($column, $order)->select();
  2480. }
  2481. return true;
  2482. }
  2483. /**
  2484. * 获取绑定的参数 并清空
  2485. * @access public
  2486. * @return array
  2487. */
  2488. public function getBind()
  2489. {
  2490. $bind = $this->bind;
  2491. $this->bind = [];
  2492. return $bind;
  2493. }
  2494. /**
  2495. * 创建子查询SQL
  2496. * @access public
  2497. * @param bool $sub
  2498. * @return string
  2499. * @throws DbException
  2500. */
  2501. public function buildSql($sub = true)
  2502. {
  2503. return $sub ? '( ' . $this->select(false) . ' )' : $this->select(false);
  2504. }
  2505. /**
  2506. * 删除记录
  2507. * @access public
  2508. * @param mixed $data 表达式 true 表示强制删除
  2509. * @return int
  2510. * @throws Exception
  2511. * @throws PDOException
  2512. */
  2513. public function delete($data = null)
  2514. {
  2515. // 分析查询表达式
  2516. $options = $this->parseExpress();
  2517. $pk = $this->getPk($options);
  2518. if (isset($options['cache']) && is_string($options['cache']['key'])) {
  2519. $key = $options['cache']['key'];
  2520. }
  2521. if (!is_null($data) && true !== $data) {
  2522. if (!isset($key) && !is_array($data)) {
  2523. // 缓存标识
  2524. $key = 'think:' . $options['table'] . '|' . $data;
  2525. }
  2526. // AR模式分析主键条件
  2527. $this->parsePkWhere($data, $options);
  2528. } elseif (!isset($key) && is_string($pk) && isset($options['where']['AND'][$pk])) {
  2529. $key = $this->getCacheKey($options['where']['AND'][$pk], $options, $this->bind);
  2530. }
  2531. if (true !== $data && empty($options['where'])) {
  2532. // 如果条件为空 不进行删除操作 除非设置 1=1
  2533. throw new Exception('delete without condition');
  2534. }
  2535. // 生成删除SQL语句
  2536. $sql = $this->builder->delete($options);
  2537. // 获取参数绑定
  2538. $bind = $this->getBind();
  2539. if ($options['fetch_sql']) {
  2540. // 获取实际执行的SQL语句
  2541. return $this->connection->getRealSql($sql, $bind);
  2542. }
  2543. // 检测缓存
  2544. if (isset($key) && Cache::get($key)) {
  2545. // 删除缓存
  2546. Cache::rm($key);
  2547. } elseif (!empty($options['cache']['tag'])) {
  2548. Cache::clear($options['cache']['tag']);
  2549. }
  2550. // 执行操作
  2551. $result = $this->execute($sql, $bind);
  2552. if ($result) {
  2553. if (!is_array($data) && is_string($pk) && isset($key) && strpos($key, '|')) {
  2554. list($a, $val) = explode('|', $key);
  2555. $item[$pk] = $val;
  2556. $data = $item;
  2557. }
  2558. $options['data'] = $data;
  2559. $this->trigger('after_delete', $options);
  2560. }
  2561. return $result;
  2562. }
  2563. /**
  2564. * 分析表达式(可用于查询或者写入操作)
  2565. * @access protected
  2566. * @return array
  2567. */
  2568. protected function parseExpress()
  2569. {
  2570. $options = $this->options;
  2571. // 获取数据表
  2572. if (empty($options['table'])) {
  2573. $options['table'] = $this->getTable();
  2574. }
  2575. if (!isset($options['where'])) {
  2576. $options['where'] = [];
  2577. } elseif (isset($options['view'])) {
  2578. // 视图查询条件处理
  2579. foreach (['AND', 'OR'] as $logic) {
  2580. if (isset($options['where'][$logic])) {
  2581. foreach ($options['where'][$logic] as $key => $val) {
  2582. if (array_key_exists($key, $options['map'])) {
  2583. $options['where'][$logic][$options['map'][$key]] = $val;
  2584. unset($options['where'][$logic][$key]);
  2585. }
  2586. }
  2587. }
  2588. }
  2589. if (isset($options['order'])) {
  2590. // 视图查询排序处理
  2591. if (is_string($options['order'])) {
  2592. $options['order'] = explode(',', $options['order']);
  2593. }
  2594. foreach ($options['order'] as $key => $val) {
  2595. if (is_numeric($key)) {
  2596. if (strpos($val, ' ')) {
  2597. list($field, $sort) = explode(' ', $val);
  2598. if (array_key_exists($field, $options['map'])) {
  2599. $options['order'][$options['map'][$field]] = $sort;
  2600. unset($options['order'][$key]);
  2601. }
  2602. } elseif (array_key_exists($val, $options['map'])) {
  2603. $options['order'][$options['map'][$val]] = 'asc';
  2604. unset($options['order'][$key]);
  2605. }
  2606. } elseif (array_key_exists($key, $options['map'])) {
  2607. $options['order'][$options['map'][$key]] = $val;
  2608. unset($options['order'][$key]);
  2609. }
  2610. }
  2611. }
  2612. }
  2613. if (!isset($options['field'])) {
  2614. $options['field'] = '*';
  2615. }
  2616. if (!isset($options['data'])) {
  2617. $options['data'] = [];
  2618. }
  2619. if (!isset($options['strict'])) {
  2620. $options['strict'] = $this->getConfig('fields_strict');
  2621. }
  2622. foreach (['master', 'lock', 'fetch_pdo', 'fetch_sql', 'distinct'] as $name) {
  2623. if (!isset($options[$name])) {
  2624. $options[$name] = false;
  2625. }
  2626. }
  2627. foreach (['join', 'union', 'group', 'having', 'limit', 'order', 'force', 'comment'] as $name) {
  2628. if (!isset($options[$name])) {
  2629. $options[$name] = '';
  2630. }
  2631. }
  2632. if (isset($options['page'])) {
  2633. // 根据页数计算limit
  2634. list($page, $listRows) = $options['page'];
  2635. $page = $page > 0 ? $page : 1;
  2636. $listRows = $listRows > 0 ? $listRows : (is_numeric($options['limit']) ? $options['limit'] : 20);
  2637. $offset = $listRows * ($page - 1);
  2638. $options['limit'] = $offset . ',' . $listRows;
  2639. }
  2640. $this->options = [];
  2641. return $options;
  2642. }
  2643. /**
  2644. * 注册回调方法
  2645. * @access public
  2646. * @param string $event 事件名
  2647. * @param callable $callback 回调方法
  2648. * @return void
  2649. */
  2650. public static function event($event, $callback)
  2651. {
  2652. self::$event[$event] = $callback;
  2653. }
  2654. /**
  2655. * 触发事件
  2656. * @access protected
  2657. * @param string $event 事件名
  2658. * @param mixed $params 额外参数
  2659. * @return bool
  2660. */
  2661. protected function trigger($event, $params = [])
  2662. {
  2663. $result = false;
  2664. if (isset(self::$event[$event])) {
  2665. $callback = self::$event[$event];
  2666. $result = call_user_func_array($callback, [$params, $this]);
  2667. }
  2668. return $result;
  2669. }
  2670. }