Base.php 59 KB

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