Query.php 105 KB

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