Query.php 94 KB

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