Query.php 96 KB

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