Base.php 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925
  1. <?php
  2. namespace Qii\Driver\Entity;
  3. use Qii\Driver\Model;
  4. use Qii\Driver\Response;
  5. class Base {
  6. /**
  7. * 字段及值
  8. *
  9. * @var array $properties
  10. */
  11. public static $properties;
  12. /**
  13. * 配置信息
  14. *
  15. * @var array $config
  16. */
  17. public static $config;
  18. /**
  19. * @var Model $db
  20. */
  21. public static $db = null;
  22. /**
  23. * 主键
  24. * @var mix $privateKeys null
  25. */
  26. public static $privateKeys = null;
  27. /**
  28. * 唯一字段
  29. *
  30. * @var array $uniqKeys
  31. */
  32. public static $uniqKeys = null;
  33. /**
  34. * 设置排除项
  35. *
  36. * @var array $exclude
  37. */
  38. public static $exclude = [];
  39. /**
  40. * @var string 表别名
  41. */
  42. private $alias;
  43. private $nullFields = [];
  44. /**
  45. * hooker for fields 查询字段/ where 查询条件 / order 排序 / cache 缓存 / with 关联查询
  46. * @var array $hooker
  47. */
  48. private $hooker = array();
  49. /**
  50. * 默认过期时间
  51. *
  52. * @var int $defaultExpired
  53. */
  54. private $defaultExpired = 600;
  55. /**
  56. * 当前执行的sql
  57. *
  58. * @var string
  59. */
  60. private $calledSQL = "";
  61. /**
  62. * 最后插入数据的自增ID
  63. *
  64. * @var int $lastInsertID
  65. */
  66. private $lastInsertID;
  67. public function __construct(){
  68. $this->cleanVars();
  69. }
  70. final public function cleanVars() {
  71. self::$uniqKeys = null;
  72. self::$privateKeys = null;
  73. self::$exclude = [];
  74. }
  75. /**
  76. * 默认值,仅在新增数据的时候支持,更新不支持
  77. *
  78. * @return array
  79. */
  80. public function defaultFieldsValue(){}
  81. /**
  82. * 返回 table 的名字,以便分库分表的时候指定使用
  83. *
  84. * @return mixed
  85. * @throws \Exception
  86. */
  87. public function getTable() {
  88. throw new \Exception('请先设置需要保存的数据表');
  89. }
  90. /**
  91. * 当前表名别名
  92. *
  93. * @param string $name
  94. * @return $this
  95. */
  96. public function alias($name) {
  97. $this->alias = $name;
  98. return $this;
  99. }
  100. /**
  101. * 预处理表名
  102. *
  103. * @return mixed|string
  104. * @throws \Exception
  105. */
  106. public function prepareTable() {
  107. if($this->alias == '') {
  108. return $this->getTable();
  109. }
  110. return $this->getTable() . ' ' . $this->alias;
  111. }
  112. /**
  113. * set hooker for method
  114. * 目前 where 和 order 及 fields 支持
  115. * @param $key
  116. * @param $hooker
  117. * @return $this
  118. */
  119. protected function setHooker($key, $hooker, $args) {
  120. $this->hooker[$key]['func'] = $hooker;
  121. $this->hooker[$key]['args'] = $args;
  122. return $this;
  123. }
  124. /**
  125. * or 查询
  126. * @param array | string $condition 条件
  127. * @param mixed $args 参数
  128. * @return $this
  129. * @throws \Exception
  130. */
  131. final public function or($condition, $args = null) {
  132. $this->setOrHooker(function($or) use($condition){
  133. if(is_array($condition)) {
  134. $or = array_merge($or, $condition);
  135. return $or;
  136. }
  137. return $condition;
  138. });
  139. return $this;
  140. }
  141. /**
  142. * Or Hooker
  143. * @param $hooker
  144. * @param $args
  145. * @return $this
  146. * @throws \Exception
  147. */
  148. public function setOrHooker($hooker, $args = null){
  149. $this->checkCallable($hooker);
  150. if(!isset($this->hooker['or'])) {
  151. $this->hooker['or'] = [];
  152. }
  153. $this->hooker['or'][] = ['func' => $hooker, 'args' => $args];
  154. return $this;
  155. }
  156. /**
  157. * 获取or条件
  158. *
  159. * @return array
  160. */
  161. public function getOrHooker() {
  162. $or = [];
  163. if(isset($this->hooker['or'])) {
  164. foreach ($this->hooker['or'] as $value) {
  165. if(is_callable($value['func'])) {
  166. $or[] = call_user_func($value['func'], [], $value['args']);
  167. }
  168. }
  169. }
  170. return $or;
  171. }
  172. /**
  173. * where 条件
  174. * @param array $where where条件
  175. * @param mixed $args 参数
  176. * @return $this
  177. * @throws \Exception
  178. */
  179. final public function where($where, $args = null) {
  180. $this->setWhereHooker(function($w) use($where){
  181. if(is_array($where)) {
  182. $w = array_merge($w, $where);
  183. return $w;
  184. }
  185. return $where;
  186. }, $args);
  187. return $this;
  188. }
  189. /**
  190. * 设置where hooker
  191. * @param object $hooker
  192. * @return $this
  193. * @throws \Exception
  194. */
  195. public function setWhereHooker($hooker, $args = null) {
  196. $this->checkCallable($hooker);
  197. $this->setHooker('where', $hooker, $args);
  198. return $this;
  199. }
  200. /**
  201. * 获取where条件
  202. *
  203. * @return array|mixed
  204. */
  205. public function getWhereHooker() {
  206. $where = $this->properties();
  207. if(isset($this->hooker['where']) && is_callable($this->hooker['where']['func'])) {
  208. if($this->alias != ""){
  209. foreach ($where as $key => $value) {
  210. if(!preg_match("/{$this->alias}\.{$key}/", $key)) {
  211. $where[$this->alias .'.'. $key] = $value;
  212. unset($where[$key]);
  213. }
  214. }
  215. }
  216. $where = call_user_func($this->hooker['where']['func'], $where, $this->hooker['where']['args']);
  217. }
  218. return $where;
  219. }
  220. /**
  221. * join 条件
  222. * @param mixed $join 条件
  223. * @param mixed $args 参数
  224. * @return $this
  225. * @throws \Exception
  226. */
  227. final public function join($join, $args = null) {
  228. $this->setJoinHooker(function($j) use($join){
  229. $j[] = $join;
  230. return $j;
  231. }, $args);
  232. return $this;
  233. }
  234. /**
  235. * join hooker
  236. * @param \Closure $hooker
  237. * @param mix $args
  238. * @return $this
  239. * @throws \Exception
  240. */
  241. public function setJoinHooker($hooker, $args = null) {
  242. $this->checkCallable($hooker);
  243. if(!isset($this->hooker['join'])) {
  244. $this->hooker['join'] = [];
  245. }
  246. $this->hooker['join'][] = ['func' => $hooker, 'args' => $args];
  247. return $this;
  248. }
  249. /**
  250. * 获取 join hooker
  251. * @return array
  252. */
  253. public function getJoinHooker() {
  254. $join = [];
  255. if(isset($this->hooker['join'])) {
  256. foreach ($this->hooker['join'] as $value) {
  257. if(is_callable($value['func'])) {
  258. $join[] = call_user_func($value['func'], [], $value['args']);
  259. }
  260. }
  261. }
  262. return $join;
  263. }
  264. /**
  265. * order by
  266. * @param array $order
  267. * @param mix $args 参数
  268. * @return $this
  269. * @throws \Exception
  270. */
  271. final public function order($order, $args = null) {
  272. $this->setOrderHooker(function() use($order) {
  273. return $order;
  274. }, $args);
  275. return $this;
  276. }
  277. /**
  278. * 设置order by hooker
  279. * @param object $hooker
  280. * @return $this
  281. * @throws \Exception
  282. */
  283. public function setOrderHooker($hooker, $args = null) {
  284. $this->checkCallable($hooker);
  285. $this->setHooker('order', $hooker, $args);
  286. return $this;
  287. }
  288. /**
  289. * limit
  290. * @param array $limit [page, limit]
  291. * @param mixed $args 参数
  292. * @return $this
  293. * @throws \Exception
  294. */
  295. final public function limit($limit, $args = null) {
  296. $this->setLimitHooker(function() use($limit){
  297. return $limit;
  298. }, $args);
  299. return $this;
  300. }
  301. /**
  302. * 设置 limit hooker
  303. *
  304. * @param object $hooker
  305. * @return $this
  306. * @throws \Exception
  307. */
  308. public function setLimitHooker($hooker, $args = null) {
  309. $this->checkCallable($hooker);
  310. $this->setHooker('limit', $hooker, $args);
  311. return $this;
  312. }
  313. /**
  314. * 获取limit
  315. * @return int|mixed
  316. */
  317. public function getLimitHooker() {
  318. if(isset($this->hooker['limit']) && is_callable($this->hooker['limit']['func'])) {
  319. return call_user_func($this->hooker['limit']['func'], [], $this->hooker['limit']['args']);
  320. }
  321. return [];
  322. }
  323. /**
  324. * 设置缓存插件
  325. *
  326. * @param Cache $cache 缓存类
  327. * @return $this
  328. * @throws \Exception
  329. */
  330. final public function cache($cache) {
  331. $this->setCacheHooker(function() use($cache){
  332. return $cache;
  333. });
  334. return $this;
  335. }
  336. /**
  337. * 设置 cache hooker
  338. *
  339. * @param callable $hooker
  340. * @param array| mixed $args
  341. * @return $this
  342. * @throws \Exception
  343. */
  344. public function setCacheHooker($hooker, $args = null) {
  345. $this->checkCallable($hooker);
  346. $this->setHooker('cache', $hooker, $args);
  347. return $this;
  348. }
  349. /**
  350. * 获取Cache Hooker
  351. * @return mixed|null[]
  352. */
  353. public function getCacheHooker() {
  354. if(isset($this->hooker['cache']) && is_callable($this->hooker['cache']['func'])) {
  355. return call_user_func($this->hooker['cache']['func'], [], $this->hooker['cache']['args']);
  356. }
  357. return [null, null, null];
  358. }
  359. /**
  360. * 缓存设置
  361. *
  362. * @param array $config 缓存配置
  363. * @return void
  364. */
  365. public function setCacheConfig($config) {
  366. if(!is_array($config)) {
  367. return;
  368. }
  369. self::$config['cache'] = $config;
  370. }
  371. /**
  372. * 获取缓存的配置信息
  373. *
  374. * @return array
  375. */
  376. public function getCacheConfig() {
  377. if(is_array(self::$config) && isset(self::$config['cache']) && is_array(self::$config['cache'])) {
  378. return self::$config['cache'];
  379. }
  380. return array();
  381. }
  382. /**
  383. * with
  384. *
  385. * @param array $with 获取信息 [$rel, 'with name', 'hasOne/hasMany', 'key', 'rel_pri_key']
  386. * @return $this
  387. * @throws \Exception
  388. */
  389. public function with($with) {
  390. $this->setWith(function ()use($with){
  391. return $with;
  392. });
  393. return $this;
  394. }
  395. /**
  396. * 设置关联子查询
  397. *
  398. * @param $hooker [关联对象, 返回数据key, hasOne/hasMany, 主键, rel 主键]
  399. * @params $args
  400. * @return $this
  401. * @throws \Exception
  402. */
  403. public function setWith($hooker, $args = null){
  404. $this->checkCallable($hooker);
  405. if(!isset($this->hooker['with'])) {
  406. $this->hooker['with'] = [];
  407. }
  408. $this->hooker['with'][] = ['func' => $hooker, 'args' => $args];
  409. return $this;
  410. }
  411. /**
  412. * 获取with hooker
  413. *
  414. * @return array
  415. */
  416. public function getWithHooker() {
  417. $callback = [];
  418. if(isset($this->hooker['with'])) {
  419. foreach ($this->hooker['with'] AS $hooker) {
  420. if(is_callable($hooker['func'])) {
  421. $callback[] = call_user_func($hooker['func'], [], $hooker['args']);
  422. }
  423. }
  424. }
  425. return $callback;
  426. }
  427. /**
  428. * 如果hooker不可调用即抛出异常
  429. *
  430. * @param object $hooker
  431. * @return void
  432. * @throws \Exception
  433. */
  434. private function checkCallable($hooker) {
  435. if($hooker && !is_callable($hooker)) {
  436. throw new \Exception('Hooker is uncallable');
  437. }
  438. }
  439. /**
  440. * 设置order by hooker
  441. * @param object $hooker
  442. * @return void
  443. * @throws \Exception
  444. */
  445. public function setQueryFieldsHooker($hooker, $args = null) {
  446. if(!is_callable($hooker)) {
  447. throw new \Exception('Hooker is un callable');
  448. }
  449. $this->setHooker('fields', $hooker, $args);
  450. }
  451. /**
  452. * 通过field hooker返回查询的字段
  453. *
  454. * @return mixed|string
  455. */
  456. public function getFieldsHooker() {
  457. if(isset($this->hooker['fields']) && is_callable($this->hooker['fields']['func'])) {
  458. return call_user_func($this->hooker['fields']['func'], [], $this->hooker['fields']['args']);
  459. }
  460. return '*';
  461. }
  462. /**
  463. * 获取指定field的值
  464. * @param string $field
  465. * @return mixed
  466. */
  467. public function getFieldVal($field) {
  468. if(!preg_match('/^[a-zA-Z]/', $field)) {
  469. throw new \Exception('Field is illegal');
  470. }
  471. $property = $this->entity()->convertToProperty($field);
  472. return $this->{$property};
  473. }
  474. /**
  475. * 返回使用的db信息
  476. *
  477. * @return \Qii\Driver\Base
  478. */
  479. public function db() {
  480. if(self::$db !== null && self::$db instanceof Model) {
  481. return self::$db;
  482. }
  483. return _loadClass('\Qii\Driver\Model');
  484. }
  485. /**
  486. * DB 必须是Model类型
  487. *
  488. * @param $db
  489. * @return void
  490. * @throws \Exception
  491. */
  492. final public function setDB($db) {
  493. if(!($db instanceof \Qii\Driver\Model)) {
  494. throw new \Exception('DB is illegal');
  495. }
  496. self::$db = $db;
  497. }
  498. /**
  499. * 返回 entity 信息
  500. * @return mixed
  501. */
  502. public function entity() {
  503. return _loadClass('\Qii\Driver\Entity\Entity');
  504. }
  505. /**
  506. * 设置查询字段
  507. *
  508. * @param array|string $fields 字段名称
  509. * @param $args
  510. * @return void
  511. * @throws \Exception
  512. */
  513. final public function field($fields, $args = null) {
  514. $this->setQueryFieldsHooker(function() use($fields){
  515. return $fields;
  516. }, $args);
  517. }
  518. /**
  519. * 返回所有 Fields
  520. * @return array
  521. */
  522. public function fields()
  523. {
  524. return [];
  525. }
  526. /**
  527. * 设置唯一字段
  528. *
  529. * @param mixed $uniqKeys 唯一字段
  530. * @return void
  531. */
  532. public function setUniqKeys($uniqKeys) {
  533. self::$uniqKeys = $uniqKeys;
  534. }
  535. /**
  536. * unique (unique 如果是 array 则表示 联合唯一,如果是string则是任意唯一,多个单独唯一使用字符串以逗号隔开, 主键除外)
  537. *
  538. * @return mixed
  539. * @throws \Exception
  540. */
  541. public function uniqueKey(){
  542. if(self::$uniqKeys !== null) {
  543. return self::$uniqKeys;
  544. }
  545. throw new \Exception('请设置唯一值');
  546. }
  547. /**
  548. * 设置主键
  549. *
  550. * @param mixed $privateKeys
  551. * @return void
  552. */
  553. public function setPrivateKey($privateKeys){
  554. self::$privateKeys = $privateKeys;
  555. }
  556. /**
  557. * 主键
  558. *
  559. * @return mixed
  560. * @throws \Exception
  561. */
  562. public function primaryKey(){
  563. if(self::$privateKeys !== null) {
  564. return self::$privateKeys;
  565. }
  566. throw new \Exception('请设置主键');
  567. }
  568. /**
  569. * 设置排除项
  570. * @param array $exclude
  571. * @return void
  572. */
  573. public function setExclude($exclude) {
  574. if(!is_array($exclude)) {
  575. return;
  576. }
  577. self::$exclude = $exclude;
  578. }
  579. /**
  580. * 保存数据的时候,验证唯一需要排除的值,此处仅支持,单个或联合排除,不支持单个异或排除
  581. *
  582. * @return array
  583. */
  584. public function exclude(){
  585. if(self::$exclude !== null) {
  586. return self::$exclude;
  587. }
  588. return array();
  589. }
  590. /**
  591. * order by
  592. * @return string[]
  593. */
  594. public function orderBy() {
  595. return array();
  596. }
  597. /**
  598. * explode string
  599. * @param string $separator 分隔符
  600. * @param string $string 分割的字符串
  601. * @param int $limit 是否
  602. * @return array|false|string[]
  603. */
  604. public function explode($separator, $string, $limit = PHP_INT_MAX) {
  605. if($string == '') {
  606. return [];
  607. }
  608. return explode($separator, $string, $limit);
  609. }
  610. /**
  611. * 添加数据验证字段
  612. *
  613. * $fields = [];
  614. * return $this->valid($fields);
  615. *
  616. * @return mixed
  617. * @throws \Exception
  618. */
  619. public function validFieldsForAdd(){
  620. throw new \Exception('请设置插入数据验证的字段,格式如:["Id", "Title"],Id和Title为entity的属性');
  621. }
  622. /**
  623. * 更新数据验证字段
  624. *
  625. * $fields = [];
  626. * return $this->valid($fields);
  627. *
  628. * @return mixed
  629. * @throws \Exception
  630. */
  631. public function validFieldsForUpdate() {
  632. throw new \Exception('请设置更新数据验证的字段,格式如:["Id", "Title"],Id和Title为entity的属性');
  633. }
  634. /**
  635. * 设置需要更新为空的字段列表
  636. *
  637. * @param $fields
  638. * @return $this
  639. */
  640. public function setNull($fields) {
  641. $tableFields = $this->fields();
  642. foreach ($fields AS $field) {
  643. if(!in_array($field, $tableFields)) {
  644. continue;
  645. }
  646. $field = $this->entity()->convertToProperty($field);
  647. $this->nullFields[] = $field;
  648. }
  649. return $this;
  650. }
  651. /**
  652. * 获取不为空的属性
  653. *
  654. * @return array
  655. */
  656. public function properties() {
  657. $class = get_called_class();
  658. $method = new \ReflectionClass($class);
  659. $properties = $method->getproperties();
  660. $fields = [];
  661. foreach($properties as $property) {
  662. if($property->isPublic() && !$property->isStatic()) {
  663. $name = $property->getName();
  664. if(!isset($this->$name)) {
  665. continue;
  666. }
  667. $field = $this->entity()->convertToField($name);
  668. $fields[$field] = $this->$name;
  669. }
  670. }
  671. if(count($this->nullFields) > 0) {
  672. foreach ($this->nullFields AS $field) {
  673. $field = $this->entity()->convertToField($field);
  674. $fields[$field] = null;
  675. }
  676. }
  677. return $fields;
  678. }
  679. /**
  680. * 获取默认值
  681. *
  682. * @return array
  683. */
  684. public function getDefaultValue() {
  685. $default = [];
  686. $defaultValue = $this->defaultFieldsValue();
  687. if(!$defaultValue || !is_array($defaultValue) || count($defaultValue) == 0) {
  688. return $default;
  689. }
  690. foreach ($defaultValue as $key => $value) {
  691. $field = $this->entity()->convertToField($key);
  692. $default[$field] = $value;
  693. }
  694. return $default;
  695. }
  696. /**
  697. * 获取总行数
  698. *
  699. * @return mixed
  700. * @throws \Exception
  701. */
  702. public function count() {
  703. $query = $this->createQuery();
  704. $query->fields(' COUNT(1) as count');
  705. return $query->selectOne($this->prepareTable());
  706. }
  707. /**
  708. * 检查是否有对应的属性
  709. *
  710. * @param $key
  711. * @return bool
  712. * @throws \ReflectionException
  713. */
  714. public function hasProperty($key) {
  715. $class = get_called_class();
  716. $key = $this->entity()->convertToProperty($key);
  717. if(isset(self::$properties[$class])) {
  718. return isset(self::$properties[$class][$key]);
  719. }
  720. $method = new \ReflectionClass($class);
  721. $properties = $method->getproperties();
  722. $fields = array();
  723. foreach($properties as $property) {
  724. if($property->isPublic()) {
  725. $name = $property->getName();
  726. $fields[$name] = '';
  727. }
  728. }
  729. self::$properties[$class] = $fields;
  730. return isset($fields[$key]);
  731. }
  732. /**
  733. * bind value
  734. * @param $values
  735. * @return $this
  736. * @throws \ReflectionException
  737. */
  738. public function bindValues($values) {
  739. if(!is_array($values)) {
  740. return $this;
  741. }
  742. foreach ($values as $key => $value) {
  743. $property = $this->entity()->convertToProperty($key);
  744. if($this->hasProperty($key)) {
  745. $this->$property = $value;
  746. }
  747. }
  748. return $this;
  749. }
  750. /**
  751. * 回去当前执行的sql
  752. *
  753. * @return string
  754. */
  755. public function getCalledSQL() {
  756. return $this->calledSQL;
  757. }
  758. /**
  759. * 获取数据
  760. *
  761. * @return Object
  762. * @throws \Exception
  763. */
  764. public function get() {
  765. $class = get_called_class();
  766. $obj = new $class();
  767. $response = $this->info();
  768. if($response->isError()) {
  769. $obj->__Error = $response->getResult();
  770. return $obj;
  771. }
  772. $info = $response->getResult()['body'];
  773. if(!$info) {
  774. return $obj;
  775. }
  776. foreach ($info as $key => $val) {
  777. $key = $this->entity()->convertToProperty($key);
  778. $obj->$key = $val;
  779. }
  780. return $obj;
  781. }
  782. /**
  783. * get 是否返回了错误
  784. *
  785. * @return bool
  786. */
  787. public function isError() {
  788. if(isset($this->__Error)) {
  789. return true;
  790. }
  791. return false;
  792. }
  793. /**
  794. * get 返回的code
  795. *
  796. * @return int
  797. */
  798. public function getCode() {
  799. if(!$this->isError()) {
  800. return 0;
  801. }
  802. return isset($this->__Error['code']) ? $this->__Error['code'] : 0;
  803. }
  804. /**
  805. * get 返回的msg
  806. *
  807. * @return string
  808. */
  809. public function getMessage() {
  810. if(!$this->isError()) {
  811. return '';
  812. }
  813. return isset($this->__Error['msg']) ? $this->__Error['msg'] : '';
  814. }
  815. /**
  816. * 与get不同的这个返回的是Response
  817. *
  818. * @return mixed|Response
  819. */
  820. public function info() {
  821. try{
  822. $query = $this->createQuery();
  823. $info = $query->selectRow($this->prepareTable());
  824. $this->calledSQL = $query->modelSQL;
  825. if($info) $this->withRow($info);
  826. return Response::Success(static::class .'::'. __FUNCTION__,
  827. [
  828. '_result' => ['code' => Response::DO_SUCCESS, 'msg' => '获取成功', 'body' => $info]
  829. ]
  830. );
  831. }catch (\Exception $e) {
  832. return Response::Fail(static::class .'::'. __FUNCTION__,
  833. [
  834. '_result' => ['code' => Response::FAIL_FOR_SELECT, 'msg' =>$e->getMessage(), 'body' => []],
  835. 'message' => $e->getMessage()
  836. ]
  837. );
  838. }
  839. }
  840. /**
  841. * 将表对象对应的字段转换成array
  842. *
  843. * @return array
  844. */
  845. public function toArray($returnFields = false)
  846. {
  847. $arr = [];
  848. $method = new \ReflectionClass($this);
  849. $vars = [];
  850. foreach ($this as $k => $t) {
  851. if(preg_match("/^[A-Z]+/", $k)) {
  852. $vars[] = $k;
  853. }
  854. }
  855. $fields = $this->fields();
  856. if(count($fields)) {
  857. if($returnFields) {
  858. foreach ($fields as $key => $value) {
  859. $arr['__fields__'][$key] = $value;
  860. }
  861. }
  862. foreach ($vars as $extra) {
  863. if(!isset($arr[$extra])) {
  864. $field = $this->entity()->convertToField($extra);
  865. if(isset($this->$extra)) $arr[$field] = $this->$extra;
  866. }
  867. }
  868. return $arr;
  869. }
  870. $properties = $method->getproperties();
  871. foreach($properties as $property) {
  872. if($property->isPublic() && !$property->isStatic()) {
  873. $name = $property->getName();
  874. $field = $this->entity()->convertToField($name);
  875. if(isset($this->$name)) $arr[$field] = $this->$name;
  876. continue;
  877. }
  878. //移除非public的变量
  879. $i = array_search($property->getName(), $vars);
  880. if($i !== false) {
  881. array_splice($vars, $i, 1);
  882. }
  883. }
  884. foreach ($vars as $extra) {
  885. if(!isset($arr[$extra])) {
  886. $field = $this->entity()->convertToField($extra);
  887. if(isset($this->$extra)) $arr[$field] = $this->$extra;
  888. }
  889. }
  890. return $arr;
  891. }
  892. /**
  893. * 是否相关数据存在
  894. *
  895. * @return bool
  896. */
  897. public function exist() {
  898. $where = $this->getWhereHooker();
  899. if(!$where) {
  900. return false;
  901. }
  902. return (bool) $this->db()->where($where)->selectOne($this->prepareTable());
  903. }
  904. /**
  905. * 保存数据
  906. *
  907. * @return mixed|Qii\Driver\Response
  908. * @throws \Exception
  909. */
  910. public function add() {
  911. $valid = $this->validFieldsForAdd();
  912. if($valid->isError()) {
  913. return $valid;
  914. }
  915. //如果设置了 unique 就先验证唯一性
  916. list($uniqueWhere, $uniqueOr, $exclude, $primary) = $this->condition();
  917. unset($exclude);
  918. //如果 $where $or 为空,看看主键是否有设置值,有设置值说明验证主键就可以,反之设置了主键,主键值设置了,只验证主键就可以了
  919. if(count($primary) > 0) {
  920. $exist = $this->db()->limit(1)->where($primary)->selectRow($this->prepareTable());
  921. if($exist) {
  922. return Response::Exist(static::class .'::'. __FUNCTION__,
  923. [
  924. '_result' => ['code' => Response::DOES_EXIST, 'msg' => '数据已经存在', 'body' => $exist],
  925. 'message' => '数据已经存在'
  926. ]
  927. );
  928. }
  929. }
  930. if(count($uniqueWhere) > 0 || count($uniqueOr) > 0) {
  931. $exist = $this->db()->limit(1)->where($uniqueWhere)->orTerms($uniqueOr)->selectRow($this->prepareTable());
  932. if($exist) {
  933. return Response::Exist(static::class .'::'. __FUNCTION__,
  934. [
  935. '_result' => ['code' => Response::DOES_EXIST, 'msg' => '数据已经存在', 'body' => $exist],
  936. 'message' => '数据已存在'
  937. ]
  938. );
  939. }
  940. }
  941. $values = array_merge($this->getDefaultValue(), $this->properties());
  942. $this->lastInsertID = $res = $this->db()->insertObject($this->prepareTable(), $values);
  943. if($this->db()->isError()) {
  944. return Response::FailSave(static::class .'::'. __FUNCTION__,
  945. [
  946. '_result' => ['code' => Response::FAIL_FOR_SAVE, 'msg' => $this->db()->getMessage(), 'body' => []],
  947. 'message' => $this->db()->getMessage()
  948. ]);
  949. }
  950. return Response::Success(static::class .'::'. __FUNCTION__,
  951. [
  952. '_result' => ['code' => Response::DO_SUCCESS, 'msg' => '添加成功', 'body' => $res]
  953. ]
  954. );
  955. }
  956. /**
  957. * 获取最后一条插入记录的自增ID
  958. *
  959. * @return mixed
  960. */
  961. final public function lastInsertID() {
  962. return $this->lastInsertID;
  963. }
  964. /**
  965. * 删除指定数据
  966. *
  967. * @return false|Response
  968. */
  969. public function remove() {
  970. if(!$this->properties() && empty($this->getWhereHooker())) {
  971. return Response::Fail(static::class .'::'. __FUNCTION__,
  972. [
  973. '_result' => ['code' => Response::FAIL_FOR_VALIDATE, 'msg' => '未指定删除目标', 'body' => []],
  974. 'message' => '未指定删除目标'
  975. ]
  976. );
  977. }
  978. $properties = [];
  979. foreach ($this->properties() as $key => $val) {
  980. $properties[] = $this->entity()->convertToProperty($key);
  981. }
  982. $valid = $this->valid($properties);
  983. if($valid->isError()) {
  984. return $valid;
  985. }
  986. $query = $this->createQuery();
  987. $affectedRows = $query->delete($this->prepareTable());
  988. if($this->db()->isError()) {
  989. return Response::FailSave(static::class .'::'. __FUNCTION__,
  990. [
  991. '_result' => ['code' => Response::FAIL_FOR_SAVE, 'msg' => $this->db()->getMessage(), 'body' => []],
  992. 'message' => $this->db()->getMessage()
  993. ]
  994. );
  995. }
  996. return Response::Success(static::class .'::'. __FUNCTION__,
  997. [
  998. '_result' => ['code' => Response::DO_SUCCESS, 'msg' => '删除成功,总共删除了'. $affectedRows . '条记录', 'body' => $affectedRows],
  999. 'message' => '删除成功,总共删除了'. $affectedRows . '条记录'
  1000. ]
  1001. );
  1002. }
  1003. /**
  1004. * 更新
  1005. *
  1006. * @return mixed | Response
  1007. * @throws \Exception
  1008. */
  1009. public function update(){
  1010. $valid = $this->validFieldsForUpdate();
  1011. if($valid->isError()) {
  1012. return $valid;
  1013. }
  1014. //检查是否有重复的
  1015. list($uniqueWhere, $uniqueOr, $exclude, $primaryKey) = $this->condition();
  1016. // 检查 unique 是否已经存在相关数据
  1017. $diffWhere = array_diff_assoc($uniqueWhere, $primaryKey);
  1018. $diffOr = array_diff_assoc($uniqueOr, $primaryKey);
  1019. /*print_r(
  1020. [
  1021. 'where' => $uniqueWhere,
  1022. 'or' => $uniqueOr,
  1023. 'exclude' => $exclude,
  1024. 'primary' => $primaryKey
  1025. ]
  1026. );*/
  1027. /*$diffExclude = array_diff_assoc($exclude, $primaryKey);
  1028. print_r(
  1029. [
  1030. 'diffWhere' => $diffWhere,
  1031. 'diffOr' => $diffOr,
  1032. 'diffExclude' => $diffExclude
  1033. ]
  1034. );*/
  1035. if(count($diffWhere) > 0 || count($diffOr) > 0) {
  1036. $unique = $this->db()->limit(1)->where($diffWhere)->orTerms($diffOr)->exclude($exclude)->selectRow($this->prepareTable());
  1037. if($unique) {
  1038. return Response::Exist(static::class .'::'. __FUNCTION__,
  1039. ['_result' => ['code' => Response::DOES_EXIST, 'msg' => '已经存在相关记录', 'body' => $unique]]
  1040. );
  1041. }
  1042. }
  1043. //检查更新的数据是否存在,以主键为主
  1044. $exit = $this->db()->limit(1)->where($primaryKey)->selectOne($this->prepareTable());
  1045. if($exit === null || $exit === false) {
  1046. return Response::NotExist(static::class .'::'. __FUNCTION__,
  1047. ['_result' => ['code' => Response::DOES_NOT_EXIST, 'msg' => '未找到相关记录', 'body' => []]]
  1048. );
  1049. }
  1050. //获取默认值
  1051. //更新的时候不使用默认值
  1052. //$values = array_merge($this->getDefaultValue(), $this->properties());
  1053. $affectedRows = $this->db()->updateObject($this->prepareTable(), $this->properties(), $primaryKey);
  1054. if($this->db()->isError()) {
  1055. return Response::FailUpdate(static::class .'::'. __FUNCTION__,
  1056. [
  1057. '_result' => ['code' => Response::FAIL_FOR_UPDATE, 'msg' => $this->db()->getMessage(), 'body' => []]
  1058. ]
  1059. );
  1060. }
  1061. return Response::Success(static::class .'::'. __FUNCTION__,
  1062. [
  1063. '_result' => ['code' => Response::DO_SUCCESS, 'msg' => '数据更新成功,总共更新了'. $affectedRows . '条记录', 'body' => $affectedRows],
  1064. 'message' => '数据更新成功,总共更新了'. $affectedRows . '条记录'
  1065. ]
  1066. );
  1067. }
  1068. /**
  1069. * 更新字段
  1070. *
  1071. * @return mixed| Response
  1072. * @throws \Exception
  1073. */
  1074. public function updateFields() {
  1075. $properties = $this->properties();
  1076. $fields = $this->entity()->convertToProperties(array_keys($properties));
  1077. $valid = $this->valid($fields);
  1078. if($valid->isError()) {
  1079. return $valid;
  1080. }
  1081. list($uniqueWhere, $uniqueOr, $exclude, $primaryKey) = $this->condition();
  1082. /*print_r(
  1083. [
  1084. 'where' => $uniqueWhere,
  1085. 'or' => $uniqueOr,
  1086. 'exclude' => $exclude,
  1087. 'primary' => $primaryKey
  1088. ]
  1089. );*/
  1090. // 检查 unique 是否已经存在相关数据
  1091. $diffWhere = array_diff_assoc($uniqueWhere, $primaryKey);
  1092. $diffOr = array_diff_assoc($uniqueOr, $primaryKey);
  1093. /*$diffExclude = array_diff_assoc($exclude, $primaryKey);
  1094. print_r(
  1095. [
  1096. 'diffWhere' => $diffWhere,
  1097. 'diffOr' => $diffOr,
  1098. 'diffExclude' => $diffExclude
  1099. ]
  1100. );*/
  1101. if(count($diffWhere) > 0 || count($diffOr) > 0) {
  1102. $unique = $this->db()->limit(1)->where($diffWhere)->orTerms($diffOr)->exclude($exclude)->selectRow($this->prepareTable());
  1103. if($unique) {
  1104. return Response::Exist(static::class .'::'. __FUNCTION__,
  1105. ['_result' => ['code' => Response::DOES_EXIST, 'msg' => '已经存在相关记录', 'body' => $unique]]
  1106. );
  1107. }
  1108. }
  1109. //检查更新的数据是否存在,以主键为主
  1110. $exit = $this->db()->limit(1)->where($primaryKey)->selectOne($this->prepareTable());
  1111. if($exit === null || $exit === false) {
  1112. return Response::NotExist(static::class .'::'. __FUNCTION__,
  1113. [
  1114. '_result' => ['code' => Response::DOES_NOT_EXIST, 'msg' => '未找到相关记录', 'body' => []],
  1115. 'message' => '未找到相关记录'
  1116. ]
  1117. );
  1118. }
  1119. //获取默认值
  1120. //更新的时候不使用默认值
  1121. //$values = array_merge($this->getDefaultValue(), $this->properties());
  1122. $affectedRows = $this->db()->updateObject($this->prepareTable(), $this->properties(), $primaryKey);
  1123. if($this->db()->isError()) {
  1124. return Response::FailUpdate(static::class .'::'. __FUNCTION__,
  1125. [
  1126. '_result' => ['code' => Response::FAIL_FOR_UPDATE, 'msg' => $this->db()->getMessage(), 'body' => []],
  1127. 'message' => $this->db()->getMessage()
  1128. ]
  1129. );
  1130. }
  1131. return Response::Success(static::class .'::'. __FUNCTION__,
  1132. [
  1133. '_result' => ['code' => Response::DO_SUCCESS, 'msg' => '数据更新成功', 'body' => $affectedRows]
  1134. ]
  1135. );
  1136. }
  1137. /**
  1138. * 增加或减少某一个字段的值
  1139. *
  1140. * @return mixed|Response
  1141. * @throws \Exception
  1142. */
  1143. public function incr() {
  1144. list($where, $or, $exclude, $primary) = $this->condition();
  1145. unset($where, $or, $exclude);
  1146. $property = $this->properties();
  1147. $incr = [];
  1148. foreach ($property as $key => $value) {
  1149. if(!is_numeric($value)) {
  1150. continue;
  1151. }
  1152. $incr[$key] = $value;
  1153. }
  1154. $diff = array_diff_assoc($incr, $primary);
  1155. if(count($diff) == 0) {
  1156. return Response::Fail(self::class .'::'. __FUNCTION__,
  1157. [
  1158. '_result' => ['code' => Response::DO_FAIL, 'msg' => 'INCR 参数错误'],
  1159. 'message' => 'INCR 参数错误',
  1160. ]
  1161. );
  1162. }
  1163. $sets = [];
  1164. foreach ($diff as $key => $val) {
  1165. if($val == 0) {
  1166. $sets[$key] = $val;
  1167. }else if($val > 0) {
  1168. $sets[$key . ':plus'] = $val;
  1169. }else if($val < 0) {
  1170. $sets[$key . ':minus'] = $val * -1;
  1171. }
  1172. }
  1173. $affectedRows = $this->db()->set($sets)->where($primary)->update($this->prepareTable());
  1174. if($this->db()->isError()) {
  1175. return Response::FailUpdate(static::class .'::'. __FUNCTION__,
  1176. [
  1177. '_result' => ['code' => Response::FAIL_FOR_UPDATE, 'msg' => $this->db()->getMessage(), 'body' => []],
  1178. 'message' => $this->db()->getMessage()
  1179. ]
  1180. );
  1181. }
  1182. return Response::Success(static::class .'::'. __FUNCTION__,
  1183. [
  1184. '_result' => ['code' => Response::DO_SUCCESS, 'msg' => 'INCR 成功', 'body' => $affectedRows]
  1185. ]
  1186. );
  1187. }
  1188. /**
  1189. * 获取fields
  1190. *
  1191. * @return false|mixed|string|string[]
  1192. */
  1193. public function getFields() {
  1194. $fields = $this->getFieldsHooker();
  1195. if(!is_array($fields)) {
  1196. $fields = explode(',', preg_replace("/\s{2,}/", " ", preg_replace("/\s(~as)/", "", $fields)));
  1197. }
  1198. return $fields;
  1199. }
  1200. /**
  1201. * 获取where及or条件并创建查询条件
  1202. *
  1203. * @return \Qii\Driver\Base
  1204. */
  1205. public function createQuery($fields = []) {
  1206. if(empty($fields)) {
  1207. $fields = $this->getFields();
  1208. }
  1209. $query = $this->db()->fields($fields)->where($this->getWhereHooker())->fetchSql($this->calledSQL);
  1210. $or = $this->getOrHooker();
  1211. foreach ($or as $v) {
  1212. $query = $query->orTerms($v);
  1213. }
  1214. $join = $this->getJoinHooker();
  1215. foreach ($join as $j) {
  1216. $query = $query->join($j);
  1217. }
  1218. return $query;
  1219. }
  1220. /**
  1221. * 获取第一条数据
  1222. *
  1223. * @return mixed|Response
  1224. * @throws \Exception
  1225. */
  1226. public function first() {
  1227. $orderBy = $this->getOrderBy();
  1228. foreach ($orderBy as $key => $value) {
  1229. $orderBy[$key] = 'ASC';
  1230. }
  1231. $query = $this->createQuery();
  1232. $row = $query->limit(1)->orderBy($orderBy)->selectRow($this->prepareTable());
  1233. if($this->db()->isError()) {
  1234. return Response::Fail(static::class .'::'. __FUNCTION__,
  1235. [
  1236. '_result' => ['code' => Response::FAIL_FOR_SELECT, 'msg' => 'Query 失败' . $this->db()->getMessage(), 'body' => []],
  1237. 'message' => $this->db()->getMessage()
  1238. ]
  1239. );
  1240. }
  1241. if($row) {
  1242. $this->withRow($row);
  1243. }
  1244. return Response::Success(static::class .'::'. __FUNCTION__,
  1245. [
  1246. '_result' => ['code' => Response::DO_SUCCESS, 'msg' => 'Query 成功', 'body' => $row]
  1247. ]
  1248. );
  1249. }
  1250. /**
  1251. * 获取第一条数据
  1252. *
  1253. * @return mixed|Response
  1254. * @throws \Exception
  1255. */
  1256. public function last() {
  1257. $orderBy = $this->getOrderBy();
  1258. foreach ($orderBy as $key => $value) {
  1259. $orderBy[$key] = 'DESC';
  1260. }
  1261. $query = $this->createQuery();
  1262. $row = $query->orderBy($orderBy)->limit(1)->selectRow($this->prepareTable());
  1263. $this->calledSQL = $query->modelSQL;
  1264. if($this->db()->isError()) {
  1265. return Response::Fail(static::class .'::'. __FUNCTION__,
  1266. [
  1267. '_result' => ['code' => Response::FAIL_FOR_SELECT, 'msg' => 'Query 失败', 'body' => []],
  1268. 'messsage' => $this->db()->getMessage()
  1269. ]
  1270. );
  1271. }
  1272. if($row) {
  1273. $this->withRow($row);
  1274. }
  1275. return Response::Success(static::class .'::'. __FUNCTION__,
  1276. [
  1277. '_result' => ['code' => Response::DO_SUCCESS, 'msg' => 'Query 成功', 'body' => $row]
  1278. ]
  1279. );
  1280. }
  1281. /**
  1282. * 附带一行数据
  1283. *
  1284. * @param $row
  1285. * @return void
  1286. */
  1287. public function withRow(&$row) {
  1288. if(!is_array($row)) {
  1289. return;
  1290. }
  1291. $hooks = $this->getWithHooker();
  1292. foreach ($hooks as $with) {
  1293. if(!is_array($with) || count($with) < 5 || !is_object($with[0])) {
  1294. continue;
  1295. }
  1296. $callable = $with[0];
  1297. $relField = $with[1];
  1298. $method = $with[2];
  1299. $foreignKey = $with[3];
  1300. $associationForeignkey = $with[4];
  1301. $fields = [];
  1302. if(count($with) >= 6) {
  1303. $fields = $with[5];
  1304. }
  1305. $row[$relField] = [];
  1306. if(!isset($row[$foreignKey])) {
  1307. continue;
  1308. }
  1309. $params = [
  1310. $associationForeignkey,
  1311. [$associationForeignkey => $row[$foreignKey]],
  1312. $fields
  1313. ];
  1314. $res = call_user_func_array(array($callable, $method), $params);
  1315. if($res && isset($res[$row[$foreignKey]])) {
  1316. $row[$relField] = $res[$row[$foreignKey]];
  1317. }
  1318. }
  1319. }
  1320. /**
  1321. * 返回游标
  1322. *
  1323. * @param int | null $page 页码
  1324. * @param int | null $pageSize 页大小
  1325. * @return mixed
  1326. * @throws \Qii\Exceptions\InvalidParams
  1327. */
  1328. public function rs($page = null, $pageSize = null) {
  1329. $query = $this->createQuery()->orderBy($this->getOrderBy());
  1330. if($page && $pageSize) {
  1331. $query->limit($page, $pageSize);
  1332. }
  1333. return $query->rs($this->prepareTable());
  1334. }
  1335. /**
  1336. * select rows
  1337. * @param int $page 页码
  1338. * @param int $pageSize 页大小
  1339. * @return array
  1340. * @throws \Qii\Exceptions\InvalidParams
  1341. */
  1342. final public function select($page = null, $pageSize = null) {
  1343. $limit = $this->getLimitHooker();
  1344. if(count($limit) > 0) {
  1345. $page = $limit[0];
  1346. $pageSize = isset($limit[1]) ? $limit[1] : null;
  1347. }
  1348. $query = $this->createQuery();
  1349. $query = $query->orderBy($this->getOrderBy());
  1350. if($page !== null) {
  1351. $query = $query->limit($page, $pageSize);
  1352. }
  1353. $lists = $query->selectRows($this->prepareTable());
  1354. $this->withList($lists);
  1355. return $lists;
  1356. }
  1357. /**
  1358. * listts
  1359. * @param int $page 页码
  1360. * @param int $pageSize 页大小
  1361. * @return array
  1362. * @throws \Exception
  1363. */
  1364. public function lists($page = 1, $pageSize = 20) {
  1365. $limit = $this->getLimitHooker();
  1366. if(count($limit) > 0) {
  1367. $page = $limit[0];
  1368. $pageSize = isset($limit[1]) ? $limit[1] : null;
  1369. }
  1370. $count = $this->count();
  1371. if(!$this->initPages($data, $count, $page, $pageSize)) {
  1372. return $data;
  1373. }
  1374. /*$query = $this->createQuery();
  1375. $lists = $query->orderBy($this->getOrderBy())->limit($data['pages']['limitStart'], $pageSize)->selectRows($this->prepareTable());
  1376. $this->withList($lists);
  1377. $data['lists'] = $lists;*/
  1378. $data['lists'] = $this->select($data['pages']['limitStart'], $pageSize);
  1379. return $data;
  1380. }
  1381. /**
  1382. * 附带一行数据
  1383. *
  1384. * @param array $lists
  1385. * @return void
  1386. */
  1387. public function withList(&$lists) {
  1388. if(!is_array($lists)) {
  1389. return;
  1390. }
  1391. $hooks = $this->getWithHooker();
  1392. foreach ($hooks as $with) {
  1393. if(!is_array($with) || count($with) < 5 || !is_object($with[0])) {
  1394. continue;
  1395. }
  1396. $callable = $with[0];
  1397. $relField = $with[1];
  1398. $method = $with[2];
  1399. $foreignKey = $with[3];
  1400. $associationForeignkey = $with[4];
  1401. $fields = [];
  1402. if(count($with) == 6) {
  1403. $fields = $with[5];
  1404. }
  1405. $rel = [];
  1406. foreach ($lists as $v1) {
  1407. if(isset($v1[$foreignKey])) {
  1408. $rel[] = $v1[$foreignKey];
  1409. }
  1410. }
  1411. // [rel key, where]
  1412. $params = [
  1413. $associationForeignkey,
  1414. [$associationForeignkey . ':in' => array_unique($rel)],
  1415. $fields
  1416. ];
  1417. $res = call_user_func_array(array($callable, $method), $params);
  1418. foreach ($lists as &$v) {
  1419. if(isset($res[$v[$foreignKey]])) {
  1420. $v[$relField] = $res[$v[$foreignKey]];
  1421. }
  1422. }
  1423. }
  1424. }
  1425. /**
  1426. * 关联查询 has one
  1427. * params[rel_key, where, fields]
  1428. *
  1429. * @return array
  1430. * @throws \Exception
  1431. */
  1432. public function hasOne() {
  1433. $args = func_get_args();
  1434. $relKey = $args[0];
  1435. $fields = [];
  1436. if(count($args) == 3 && !empty($args[2])) {
  1437. $fields = $args[2];
  1438. if(!in_array($relKey, $fields)) $fields[] = $relKey;
  1439. }
  1440. if(count($fields) == 0) {
  1441. $fields = $this->getFields();
  1442. }
  1443. if(count($this->getFields()) > 0 && !in_array($relKey, $this->getFields())) {
  1444. $fields[] = $relKey;
  1445. }
  1446. $fields = array_unique($fields);
  1447. $query = $this->createQuery($fields);
  1448. $res = $query->where($args[1])->rs($this->prepareTable());
  1449. $rows = [];
  1450. foreach($res as $v) {
  1451. $rows[$v[$relKey]] = $v;
  1452. }
  1453. return $rows;
  1454. }
  1455. /**
  1456. * 关联查询
  1457. * params[rel_key, where, fields]
  1458. *
  1459. * @return array
  1460. * @throws \Exception
  1461. */
  1462. public function hasMany()
  1463. {
  1464. $args = func_get_args();
  1465. $relKey = $args[0];
  1466. $fields = [];
  1467. if(count($args) == 3 && !empty($args[2])) {
  1468. $fields = $args[2];
  1469. if(!in_array($relKey, $fields)) $fields[] = $relKey;
  1470. }
  1471. if(count($fields) == 0) {
  1472. $fields = $this->getFields();
  1473. }
  1474. if(count($this->getFields()) > 0 && !in_array($relKey, $this->getFields())) {
  1475. $fields[] = $relKey;
  1476. }
  1477. if(array_search('*', $fields) !== false) {
  1478. $fields = ['*'];
  1479. }
  1480. $query = $this->createQuery($fields);
  1481. $res = $query->where($args[1])->rs($this->prepareTable());
  1482. $rows = [];
  1483. foreach($res as $v) {
  1484. $rows[$v[$relKey]][] = $v;
  1485. }
  1486. return $rows;
  1487. }
  1488. /**
  1489. * 获取所有数据,这里不分页,但支持限条数,通过 setLimitHooker来实现
  1490. * $this->setLimitHooker(function(){
  1491. * return [x,y];//从第x条开始获取y条; return [1];//获取一条 return [0];//获取所有的
  1492. * });
  1493. * @return mixed
  1494. * @throws \Exception
  1495. */
  1496. public function listAll() {
  1497. $limit = $this->getLimitHooker();
  1498. $query = $this->createQuery()->orderBy($this->getOrderBy());
  1499. if(empty($limit) || !is_array($limit)) {
  1500. $list = $query
  1501. ->selectRows($this->prepareTable());
  1502. $this->withList($list);
  1503. return $list;
  1504. }
  1505. if(count($limit) == 1) {
  1506. $list = $query->limit($limit[0])->selectRows($this->prepareTable());
  1507. $this->withList($list);
  1508. return $list;
  1509. }
  1510. $list = $query
  1511. ->limit($limit[0], $limit[1])->selectRows($this->prepareTable());
  1512. $this->withList($list);
  1513. return $list;
  1514. }
  1515. /**
  1516. * 验证相关字段
  1517. *
  1518. * @param array $fields 字段列表
  1519. * @return Response
  1520. */
  1521. public function valid($fields = array()) {
  1522. if(!is_array($fields)) {
  1523. return Response::FailValidate(static::class .'::'. __FUNCTION__,
  1524. [
  1525. '_result' => ['code' => Response::FAIL_FOR_VALIDATE, 'msg' => '字段必须是数组', 'fields' => []],
  1526. 'message' => '字段必须是数组'
  1527. ]
  1528. );
  1529. }
  1530. $rules = $this->rules();
  1531. $result = [];
  1532. $invalidKey = [];
  1533. $values = array_merge($this->getDefaultValue(), $this->properties());
  1534. foreach ($rules as $valid => $rule) {
  1535. foreach ($rule as $val) {
  1536. $key = $this->entity()->convertToProperty($val[0]);
  1537. if(!in_array($key, $fields)) {
  1538. continue;
  1539. }
  1540. $field = $this->entity()->convertToField($key);
  1541. $verify = new Verify($val[0], $values[$field] ?? null, strtolower($valid), $val[1], $val[2] ?? '');
  1542. $res = $verify->valid();
  1543. if($res->isError()) {
  1544. $result[] = $res->getResult() .',获取的是'. ($values[$field] ?? '空');
  1545. if(!in_array($field, $invalidKey)) {
  1546. $invalidKey[] = $field;
  1547. }
  1548. }
  1549. }
  1550. }
  1551. if(count($result) > 0) {
  1552. return Response::FailValidate(static::class .'::'. __FUNCTION__,
  1553. [
  1554. '_result' => ['code' => Response::FAIL_FOR_VALIDATE, 'msg' => $result, 'fields' => $invalidKey],
  1555. 'message' => join("\n", $result)
  1556. ]
  1557. );
  1558. }
  1559. return Response::Success(static::class .'::'. __FUNCTION__, ['_result' => true]);
  1560. }
  1561. /**
  1562. * 合并多个 valid 结果 $this->valids($this->valid(['Uid']), $this->valid(['Nickname', 'Email']));
  1563. * @param ...
  1564. * @return mixed|Response
  1565. * @throws \Exception
  1566. */
  1567. public function valids() {
  1568. $validArr = func_get_args();
  1569. if(count($validArr) == 0) {
  1570. return Response::Success(static::class .'::'. __FUNCTION__, ['_result' => true]);
  1571. }
  1572. if(count($validArr) == 1) {
  1573. return $validArr[0];
  1574. }
  1575. $invalid = array();
  1576. $invalid['message'] = array();
  1577. $invalid['fields'] = array();
  1578. foreach ($validArr as $valid) {
  1579. if(!($valid instanceof Response)) {
  1580. throw new \Exception('验证结果类型必须是\Qii\Driver\Response类型');
  1581. }
  1582. if($valid->isError()) {
  1583. $result = $valid->getResult();
  1584. $invalid['message'] = array_merge($invalid['message'], $result['message']);
  1585. $invalid['fields'] = array_merge($invalid['fields'], $result['fields']);;
  1586. }
  1587. }
  1588. if(count($invalid['message']) > 0) {
  1589. return Response::Fail(static::class .'::'. __FUNCTION__, [
  1590. '_result' => ['message' => $invalid['message'], 'fields' => $invalid['fields']],
  1591. 'message' => $invalid['message']
  1592. ]);
  1593. }
  1594. return Response::Success(static::class .'::'. __FUNCTION__, ['_result' => true]);
  1595. }
  1596. /**
  1597. * unique 条件
  1598. *
  1599. * @return array[]
  1600. * @throws \Exception
  1601. */
  1602. protected function uniqueCondition() {
  1603. $uniqueWhere = [];
  1604. $uniqueOr = [];
  1605. $unique = $this->uniqueKey();
  1606. $useWhere = true;
  1607. if(!is_array($unique)) {
  1608. $unique = $this->explode(',', $unique);
  1609. $useWhere = false;
  1610. if(count($unique) == 1) {
  1611. $useWhere = true;
  1612. }
  1613. }
  1614. foreach ($unique as $key) {
  1615. $key = $this->entity()->convertToField($key);
  1616. $property = $this->entity()->convertToProperty($key);
  1617. if($useWhere) {
  1618. $uniqueWhere[$key] = $this->$property;
  1619. }else{
  1620. $uniqueOr[$key] = $this->$property;
  1621. }
  1622. }
  1623. return [$uniqueWhere, $uniqueOr];
  1624. }
  1625. /**
  1626. * exclude Condition
  1627. *
  1628. * @return array
  1629. */
  1630. protected function excludeCondition() {
  1631. $exclude = $this->exclude();
  1632. if(!$exclude) {
  1633. $exclude = $this->primaryKey();
  1634. }
  1635. if(is_array($this->exclude())) {
  1636. $exclude = $this->exclude();
  1637. }else{
  1638. $exclude = (array) $this->explode(',', $this->exclude());
  1639. }
  1640. $excludeCondition = [];
  1641. foreach ($exclude as $key) {
  1642. $field = $this->entity()->convertToField($key);
  1643. $property = $this->entity()->convertToProperty($key);
  1644. $excludeCondition[$field] = $this->$property;
  1645. }
  1646. return $excludeCondition;
  1647. }
  1648. /**
  1649. * 主键
  1650. *
  1651. * @return array
  1652. * @throws \Exception
  1653. */
  1654. protected function primaryCondition(){
  1655. $primary = array();
  1656. $primaryKey = $this->primaryKey();
  1657. if(!is_array($primaryKey)) {
  1658. $primaryKey = $this->explode(',', $primaryKey);
  1659. }
  1660. foreach ($primaryKey as $key) {
  1661. $key = $this->entity()->convertToProperty($key);
  1662. $field = $this->entity()->convertToField($key);
  1663. $value = $this->$key;
  1664. $primary[$field] = $value;
  1665. }
  1666. return $primary;
  1667. }
  1668. /**
  1669. * 获取查询条件
  1670. *
  1671. * @return array [$uniqueWhere, $uniqueOr, $excludeCondition, $primaryCondition]
  1672. */
  1673. public function condition() {
  1674. //如果设置了 unique 就先验证唯一性,保存的时候验证 uniqueKey,更新的时候验证uniqueKey并排primaryKey
  1675. //保存数据的时候验证uniqueKey;更新时验证 uniqueKey,并且排除 primaryKey,如果uniqueKey == primaryKey则不去做唯一性验证
  1676. list($uniqueWhere, $uniqueOr) = $this->uniqueCondition();
  1677. $excludeCondition = $this->excludeCondition();
  1678. $primaryCondition = $this->primaryCondition();
  1679. return [$uniqueWhere, $uniqueOr, $excludeCondition, $primaryCondition];
  1680. }
  1681. /**
  1682. * 获取order by
  1683. *
  1684. * @return array
  1685. */
  1686. public function getOrderBy() {
  1687. $order = array();
  1688. $orderBy = $this->orderBy();
  1689. if(isset($this->hooker['order']) && is_callable($this->hooker['order']['func'])) {
  1690. $orderBy = call_user_func($this->hooker['order']['func'], $order, $this->hooker['order']['args']);
  1691. }
  1692. foreach ($orderBy as $key => $val) {
  1693. $field = $this->entity()->convertToField($key);
  1694. if($this->alias != "" && strpos($field, '.') === false) {
  1695. $field = $this->alias . '.' . $field;
  1696. }
  1697. $val = strtoupper($val);
  1698. if(!in_array($val, array('DESC', 'ASC'))) {
  1699. continue;
  1700. }
  1701. $order[$field] = $val;
  1702. }
  1703. return $order;
  1704. }
  1705. /**
  1706. * 初始化page
  1707. * @param array $data 返回的数据
  1708. * @param int $count 总数量
  1709. * @param int $page 页码
  1710. * @param int $pageSize 显示数量
  1711. * @param int $pagination 分页显示最多页码
  1712. * @return bool
  1713. */
  1714. public function initPages(&$data, $count, $page, $pageSize = 20, $pagination = 5) {
  1715. $page = max(1, $page);
  1716. $pageSize = max(1, $pageSize);
  1717. $data['start'] = 0;
  1718. $data['pages'] = array('total' => 0, 'currentPage' => 0, 'totalPage' => 0);
  1719. $data['pages']['total'] = (int) ($count ? $count : 0);
  1720. $data['pages']['currentPage'] = $page;
  1721. $data['pages']['totalPage'] = ceil($data['pages']['total'] / $pageSize);
  1722. $data['lists'] = array();
  1723. if ($data['pages']['currentPage'] > $data['pages']['totalPage']) {
  1724. return false;
  1725. }
  1726. $pagination = min($pagination, $data['pages']['totalPage']);
  1727. if($data['pages']['currentPage'] - floor($pagination / 2) <= 0) {
  1728. $frames['left'] = 1;
  1729. $frames['right'] = $frames['left'] + $pagination - 1;
  1730. } else if($data['pages']['currentPage'] + floor($pagination / 2) >= $data['pages']['totalPage']) {
  1731. $frames['right'] = $data['pages']['totalPage'];
  1732. $frames['left'] = $frames['right'] - $pagination + 1;
  1733. } else {
  1734. $frames['left'] = $data['pages']['currentPage'] - floor($pagination / 2);
  1735. $frames['right'] = $data['pages']['currentPage'] + ceil($pagination / 2) - 1;
  1736. }
  1737. $data['start'] = $frames['left'];
  1738. $data['pages']['start'] = $data['start'];
  1739. $data['pages']['end'] = $frames['right'];
  1740. $data['pages']['pagination'] = $pagination;
  1741. $data['pages']['limitStart'] = (min($page, $data['pages']['totalPage']) - 1) * $pageSize;
  1742. $data['pages']['pageSize'] = (int) $pageSize;
  1743. return true;
  1744. }
  1745. /**
  1746. * response as object
  1747. *
  1748. * @return mixed|Response
  1749. */
  1750. public function response() {
  1751. $properties = $this->properties();
  1752. if(!$properties) {
  1753. return Response::Fail(static::class .'::'. __FUNCTION__,
  1754. ['_result' => ['code' => Response::FAIL_FOR_SELECT, 'msg' => '未找到相关数据', 'body' => []]
  1755. ]
  1756. );
  1757. }
  1758. return Response::Success(static::class .'::'. __FUNCTION__,
  1759. ['_result' => ['code' => Response::DO_SUCCESS, 'msg' => '获取成功', 'body' => $properties]]
  1760. );
  1761. }
  1762. /**
  1763. * 方法名 + ByCache/ByRedis/ByMemcache/会将结果缓存,这里使用的缓存类是通过hooker设置的,否则使用对应的
  1764. * ByClean 则会移除当前缓存, 默认转发到 db model上
  1765. * @param string $method method
  1766. * @param array $args
  1767. * @return mixed
  1768. */
  1769. public function __call($method, $args) {
  1770. $cache = '';
  1771. preg_match("/(byredis|bymemcache|bycache|byclean)$/i", $method, $matches);
  1772. if($matches && count($matches) > 0) {
  1773. $cache = strtolower($matches[0]);
  1774. }
  1775. if($cache && in_array($cache, ['bymemcache', 'byredis', 'bycache', 'byclean'])){
  1776. list($func, $cacheID, $config) = $this->getCacheHooker();
  1777. $policy = $this->getCacheConfig();
  1778. if($func == null) {
  1779. $func = $cache == 'bymemcache' ? $this->db()->setCache('memcached', $policy) : $this->db()->setCache('redis', $policy);
  1780. }
  1781. $method = substr($method, 0, strlen($cache) * -1);
  1782. if (method_exists($this, $method)) {
  1783. $key = get_called_class() .':'. $method .':'. substr(md5(serialize($this->properties())), -16);
  1784. if($cache == 'byclean') {
  1785. return $func->del($key);
  1786. }
  1787. if(is_object($func) && method_exists($func, 'get')) {
  1788. $res = $func->get($key);
  1789. if ($res) {
  1790. return unserialize($res);
  1791. }
  1792. }
  1793. $expiredAt = isset($config['life_time']) ? (int) $config['life_time'] :
  1794. ($policy['life_time'] ?? $this->defaultExpired);
  1795. $res = call_user_func_array(array($this, $method), $args);
  1796. $str = serialize($res);
  1797. $func->set($key, $str, ['life_time' => $expiredAt]);
  1798. return $res;
  1799. }
  1800. }
  1801. return call_user_func_array(array($this->db(), $method), $args);
  1802. }
  1803. /**
  1804. * 开始事务
  1805. *
  1806. * @return mixed
  1807. */
  1808. public function startTrans() {
  1809. return $this->db()->transaction();
  1810. }
  1811. /**
  1812. * 提交事务
  1813. *
  1814. * @return mixed
  1815. */
  1816. public function commit() {
  1817. return $this->db()->commit();
  1818. }
  1819. /**
  1820. * 回退
  1821. *
  1822. * @return mixed
  1823. */
  1824. public function rollback() {
  1825. return $this->db()->rollback();
  1826. }
  1827. /**
  1828. * 验证规则,由子类继承去修改
  1829. *
  1830. * @return array
  1831. */
  1832. public function rules()
  1833. {
  1834. return [];
  1835. }
  1836. }