Base.php 59 KB

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