Query.php 94 KB

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