Query.php 92 KB

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