BaseModel.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. <?php
  2. /// +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Models;
  12. /**
  13. * 缓存基类
  14. * @author zongjl
  15. * @date 2019/5/23
  16. * Class BaseModel
  17. * @package App\Models
  18. */
  19. class BaseModel extends CacheModel
  20. {
  21. // 创建时间
  22. const CREATED_AT = 'create_time';
  23. // 更新时间
  24. const UPDATED_AT = 'update_time';
  25. // // 删除时间
  26. // const DELETED_AT = 'delete_time';
  27. // 默认使用时间戳戳功能
  28. public $timestamps = true;
  29. // 人员ID
  30. public $userId;
  31. // 人员信息
  32. public $userInfo;
  33. // 时间
  34. public $time;
  35. /**
  36. * 构造函数
  37. * @author zongjl
  38. * @date 2019/5/30
  39. */
  40. public function __construct()
  41. {
  42. $uinfo = env("userInfo");
  43. $this->userId = $uinfo['id'];
  44. $this->userInfo = $uinfo;
  45. $this->time = time();
  46. }
  47. /**
  48. * 获取当前时间
  49. * @return int 时间戳
  50. * @author zongjl
  51. * @date 2019/5/30
  52. */
  53. public function freshTimestamp()
  54. {
  55. return time();
  56. }
  57. /**
  58. * 避免转换时间戳为时间字符串
  59. * @param mixed $value 时间
  60. * @return mixed|string|null
  61. * @author zongjl
  62. * @date 2019/5/30
  63. */
  64. public function fromDateTime($value)
  65. {
  66. return $value;
  67. }
  68. /**
  69. * 获取时间戳格式
  70. * @return string 时间戳字符串格式
  71. * @author zongjl
  72. * @date 2019/5/30
  73. */
  74. public function getDateFormat()
  75. {
  76. return 'U';
  77. }
  78. /**
  79. * 添加或编辑
  80. * @param array $data 数据源
  81. * @param string $error 异常错误信息
  82. * @param bool $is_sql 是否打印SQL
  83. * @return number 返回受影响行数据ID
  84. * @author zongjl
  85. * @date 2019/5/23
  86. */
  87. public function edit($data = [], &$error = '', $is_sql = false)
  88. {
  89. $id = isset($data['id']) ? (int)$data['id'] : 0;
  90. if ($id) {
  91. if (isset($data['update_user']) && empty($data['update_user'])) {
  92. $data['update_user'] = $this->userId;
  93. }
  94. // 置空添加时间
  95. unset($data['create_time']);
  96. // 更新时间
  97. $data['update_time'] = time();
  98. } else {
  99. // 创建时间
  100. $data['create_time'] = time();
  101. // 置空更新时间
  102. unset($data['update_time']);
  103. if (isset($data['update_user']) && empty($data['create_user'])) {
  104. $data['create_user'] = $this->userId;
  105. }
  106. }
  107. // 格式化表数据
  108. $this->formatData($data, $id);
  109. // 注册打印SQL监听事件
  110. $this->getLastSql($is_sql);
  111. // 入库处理
  112. if ($id) {
  113. // 修改数据
  114. $result = $this->where('id', $id)->update($data);
  115. // 更新ID
  116. $rowId = $id;
  117. } else {
  118. // 新增数据
  119. $result = $this->insertGetId($data);
  120. // 新增ID
  121. $rowId = $result;
  122. }
  123. if ($result !== false) {
  124. // 重置缓存
  125. if ($this->is_cache) {
  126. $data['id'] = $rowId;
  127. $this->cacheReset($rowId, $data, $id);
  128. }
  129. }
  130. return $rowId;
  131. }
  132. /**
  133. * 格式化数据
  134. * @param array $data 数组数据
  135. * @param int $id 数据记录ID
  136. * @param string $table 数据表
  137. * @return array 格式化数据
  138. * @author zongjl
  139. * @date 2019/5/24
  140. */
  141. private function formatData(&$data = [], $id = 0, $table = '')
  142. {
  143. $data_arr = [];
  144. $tables = $table ? explode(",", $table) : array($this->getTable());
  145. $item_data = [];
  146. foreach ($tables as $table) {
  147. $temp_data = [];
  148. $table_fields_list = $this->getTableFields($table);
  149. foreach ($table_fields_list as $field => $fieldInfo) {
  150. if ($field == "id") {
  151. continue;
  152. }
  153. //对强制
  154. if (isset($data[$field])) {
  155. if ($fieldInfo['Type'] == "int") {
  156. $item_data[$field] = (int)$data[$field];
  157. } else {
  158. $item_data[$field] = (string)$data[$field];
  159. }
  160. }
  161. if (!isset($data[$field]) && in_array($field, array('update_time', 'create_time'))) {
  162. continue;
  163. }
  164. //插入数据-设置默认值
  165. if (!$id && !isset($data[$field])) {
  166. $item_data[$field] = $fieldInfo['Default'];
  167. }
  168. if (isset($item_data[$field])) {
  169. $temp_data[$field] = $item_data[$field];
  170. }
  171. }
  172. $data_arr[] = $temp_data;
  173. }
  174. $data = $item_data;
  175. return $data_arr;
  176. }
  177. /**
  178. * 获取数据表字段
  179. * @param string $table 数据表名
  180. * @return array 字段数组
  181. * @author zongjl
  182. * @date 2019/5/24
  183. */
  184. private function getTableFields($table = '')
  185. {
  186. $table = $table ? $table : $this->getTable();
  187. if (strpos($table, DB_PREFIX) === false) {
  188. $table = DB_PREFIX . $table;
  189. }
  190. $field_list = \DB::select("SHOW FIELDS FROM {$table}");
  191. $info_list = [];
  192. foreach ($field_list as $row) {
  193. // 对象转数组格式
  194. $item = object_array($row);
  195. if ((strpos($item['Type'], "int") === false) || (strpos($item['Type'], "bigint") !== false)) {
  196. $type = "string";
  197. $default = $item['Default'] ? $item['Default'] : "";
  198. } else {
  199. $type = "int";
  200. $default = $item['Default'] ? $item['Default'] : 0;
  201. }
  202. $info_list[$item['Field']] = array(
  203. 'Type' => $type,
  204. 'Default' => $default
  205. );
  206. }
  207. return $info_list;
  208. }
  209. /**
  210. * 删除数据
  211. * @param int $id 删除数据ID
  212. * @param bool $is_sql 是否打印SQL
  213. * @return bool 返回true或false
  214. * @author zongjl
  215. * @date 2019/5/23
  216. */
  217. public function drop($id, $is_sql = false, $force=false)
  218. {
  219. // 注册打印SQL监听事件
  220. $this->getLastSql($is_sql);
  221. $result = $this->where('id', $id)->update(['mark' => 0]);
  222. if ($result !== false && $this->is_cache) {
  223. // 清除旧数据
  224. $this->where(UPDATED_AT,'<=', time() - 7 * 24 * 3600)->delete();
  225. // 删除成功
  226. $this->cacheDelete($id);
  227. }
  228. return $result;
  229. }
  230. /**
  231. * 查询缓存信息
  232. * @param int $id 查询数据ID
  233. * @return string 返回查询结果
  234. * @author zongjl
  235. * @date 2019/5/23
  236. */
  237. public function getInfo($id)
  238. {
  239. // 获取参数(用户提取操作人信息)
  240. $arg_list = func_get_args();
  241. $flag = isset($arg_list[0]) ? $arg_list[0] : 0;
  242. // 获取缓存信息
  243. $info = $this->getCacheFunc("info", $id);
  244. if ($info) {
  245. // 获取系统人员缓存
  246. $adminModel = new UserModel();
  247. $adminAll = $adminModel->getAll([], false, true);
  248. // 添加人
  249. if (isset($info['create_user']) && !empty($info['create_user'])) {
  250. $info['create_user_name'] = $adminAll[$info['create_user']]['realname'];
  251. }
  252. // 添加时间
  253. if (!empty($info['create_time'])) {
  254. $info['create_time'] = datetime($info['create_time'], 'Y-m-d H:i:s');
  255. }
  256. // 更新人
  257. if (isset($info['update_user']) && !empty($info['update_user'])) {
  258. $info['update_user_name'] = $adminAll[$info['update_user']]['realname'];
  259. }
  260. // 更新时间
  261. if (!empty($info['update_time'])) {
  262. $info['update_time'] = datetime($info['update_time'], 'Y-m-d H:i:s');
  263. }
  264. // 格式化信息(预留扩展方法,可不用)
  265. if (method_exists($this, 'formatInfo')) {
  266. $info = $this->formatInfo($info);
  267. }
  268. }
  269. return $info;
  270. }
  271. /**
  272. * 格式化数据
  273. * @param array $info 实体数据对象
  274. * @return array 返回实体对象
  275. * @author zongjl
  276. * @date 2019/5/23
  277. */
  278. public function formatInfo($info)
  279. {
  280. // 基类方法可不做任何操作,在子类重写即可
  281. // TODO...
  282. return $info;
  283. }
  284. /**
  285. * 查询记录总数
  286. * @param array $map 查询条件(默认:数组格式)
  287. * @param string $fields 查询字段
  288. * @param bool $is_sql 是否打印SQL
  289. * @return int 返回记录总数
  290. * @author zongjl
  291. * @date 2019/5/23
  292. */
  293. public function getCount($map = [], $fields = null, $is_sql = false)
  294. {
  295. // 注册打印SQL监听事件
  296. $this->getLastSql($is_sql);
  297. // 必备查询条件
  298. $map[] = ['mark', '=', 1];
  299. // 闭包查询条件格式化
  300. $query = $this->formatQuery($this, $map);
  301. // 链式操作
  302. if ($fields) {
  303. $count = $query->count($fields);
  304. } else {
  305. $count = $query->count();
  306. }
  307. return (int)$count;
  308. }
  309. /**
  310. * 查询某个字段的求和值
  311. * @param array $map 查询条件(默认:数组)
  312. * @param string $field 求和字段
  313. * @param bool $is_sql 是否打印SQL
  314. * @return string 返回结果
  315. * @author zongjl
  316. * @date 2019/5/23
  317. */
  318. public function getSum($map = [], $field = '', $is_sql = false)
  319. {
  320. // 注册打印SQL监听事件
  321. $this->getLastSql($is_sql);
  322. // 必备查询条件
  323. $map[] = ['mark', '=', 1];
  324. // 闭包查询条件格式化
  325. $query = $this->formatQuery($this, $map);
  326. // 链式操作
  327. $result = $query->sum($field);
  328. return $result;
  329. }
  330. /**
  331. * 查询某个字段的最大值
  332. * @param array $map 查询条件(默认:数组)
  333. * @param string $field 查询字段
  334. * @param bool $is_sql 是否打印SQL
  335. * @return string 返回结果
  336. * @author zongjl
  337. * @date 2019/5/23
  338. */
  339. public function getMax($map = [], $field = '', $is_sql = false)
  340. {
  341. // 注册打印SQL监听事件
  342. $this->getLastSql($is_sql);
  343. // 必备查询条件
  344. $map[] = ['mark', '=', 1];
  345. // 闭包查询条件格式化
  346. $query = $this->formatQuery($this, $map);
  347. // 链式操作
  348. $result = $$query->max($field);
  349. return $result;
  350. }
  351. /**
  352. * 查询某个字段的最小值
  353. * @param array $map 查询条件(默认:数组)
  354. * @param string $field 查询字典
  355. * @param bool $is_sql 是否打印SQL
  356. * @return string 返回结果
  357. * @author zongjl
  358. * @date 2019/5/23
  359. */
  360. public function getMin($map = [], $field = '', $is_sql = false)
  361. {
  362. // 注册打印SQL监听事件
  363. $this->getLastSql($is_sql);
  364. // 必备查询条件
  365. $map[] = ['mark', '=', 1];
  366. // 闭包查询条件格式化
  367. $query = $this->formatQuery($this, $map);
  368. // 链式操作
  369. $result = $query->min($field);
  370. return $result;
  371. }
  372. /**
  373. * 查询某个字段的平均值
  374. * @param array $map 查询条件(默认:数组)
  375. * @param string $field 查询字段
  376. * @param bool $is_sql 是否打印SQL
  377. * @return string 返回结果
  378. * @author zongjl
  379. * @date 2019/5/23
  380. */
  381. public function getAvg($map = [], $field = '', $is_sql = false)
  382. {
  383. // 注册打印SQL监听事件
  384. $this->getLastSql($is_sql);
  385. // 必备查询条件
  386. $map[] = ['mark', '=', 1];
  387. // 闭包查询条件格式化
  388. $query = $this->formatQuery($this, $map);
  389. // 链式操作
  390. $result = $query->avg($field);
  391. return $result;
  392. }
  393. /**
  394. * 查询某个字段的单个值
  395. * @param array $map 查询条件(默认:数组)
  396. * @param string $field 查询字段
  397. * @param bool $is_sql 是否打印SQL
  398. * @return string 返回结果
  399. * @author zongjl
  400. * @date 2019/5/23
  401. */
  402. public function getValue($map = [], $field = 'id', $is_sql = false)
  403. {
  404. // 注册打印SQL监听事件
  405. $this->getLastSql($is_sql);
  406. // 必备查询条件
  407. $map[] = ['mark', '=', 1];
  408. // 闭包查询条件格式化
  409. $query = $this->formatQuery($this, $map);
  410. // 链式操作
  411. $result = $query->value($field);
  412. return $result;
  413. }
  414. /**
  415. * 查询单条数据
  416. * @param array $map 查询条件(默认:数组)
  417. * @param string $field 查询字段(默认:全部)
  418. * @param bool $is_sql 是否打印SQL
  419. * @return array 返回结果
  420. * @author zongjl
  421. * @date 2019/5/23
  422. */
  423. public function getOne($map = [], $field = '*', $is_sql = false)
  424. {
  425. // 注册打印SQL监听事件
  426. $this->getLastSql($is_sql);
  427. // 必备查询条件
  428. $map[] = ['mark', '=', 1];
  429. // 闭包查询条件格式化
  430. $query = $this->formatQuery($this, $map);
  431. // 分析字段
  432. if (!is_array($field) && strpos($field, ',')) {
  433. $field = explode(',', $field);
  434. }
  435. // 链式操作
  436. $result = $query->select($field)->first();
  437. // 对象转数组
  438. return $result ? $result->toArray() : [];
  439. }
  440. /**
  441. * 根据记录ID获取某一行的值
  442. * @param int $id 记录ID
  443. * @param string $field 指定字段(默认:所有字段)
  444. * @param bool $is_sql 是否打印SQL
  445. * @return array 返回结果
  446. * @author zongjl
  447. * @date 2019/5/23
  448. */
  449. public function getRow($id, $field = '*', $is_sql = false)
  450. {
  451. // 注册打印SQL监听事件
  452. $this->getLastSql($is_sql);
  453. // 分析字段
  454. if (!is_array($field) && strpos($field, ',')) {
  455. $field = explode(',', $field);
  456. }
  457. // 链式操作
  458. $result = $this->where('id', $id)->select($field)->first();
  459. // 对象转数组
  460. return $result ? $result->toArray() : [];
  461. }
  462. /**
  463. * 获取某一列的值
  464. * @param array $map 查询条件
  465. * @param string $field 字段
  466. * @param bool $is_sql 是否打印SQL
  467. * @return array 返回结果
  468. * @author zongjl
  469. * @date 2019/5/29
  470. */
  471. public function getColumn($map = [], $field = 'id', $is_sql = false)
  472. {
  473. // 注册打印SQL监听事件
  474. $this->getLastSql($is_sql);
  475. // 必备查询条件
  476. $map[] = ['mark', '=', 1];
  477. // 闭包查询条件格式化
  478. $query = $this->formatQuery($this, $map);
  479. // 链式操作
  480. $result = $query->pluck($field);
  481. // 对象转数组
  482. return $result ? $result->toArray() : [];
  483. }
  484. /**
  485. * 根据条件查询单条缓存记录
  486. * @param array $map 查询条件
  487. * @param array $fields 查询字段
  488. * @param array $sort 排序
  489. * @param int $id 记录ID
  490. * @return array 结果返回值
  491. * @author zongjl
  492. * @date 2019/5/29
  493. */
  494. public function getInfoByAttr($map = [], $fields = [], $sort = [['id', 'desc']], $id = 0)
  495. {
  496. // 必备查询条件
  497. $map[] = ['mark', '=', 1];
  498. // 排除主键
  499. if ($id) {
  500. $map[] = ['id', '!=', $id];
  501. }
  502. // 闭包查询条件格式化
  503. $query = $this->formatQuery($this, $map);
  504. // 排序(支持多重排序)
  505. $query = $query->when($sort, function ($query, $sort) {
  506. foreach ($sort as $v) {
  507. $query->orderBy($v[0], $v[1]);
  508. }
  509. });
  510. // 链式操作
  511. $result = $query->select('id')->first();
  512. $result = $result ? $result->toArray() : [];
  513. // 查询缓存
  514. $data = [];
  515. if ($result) {
  516. $info = $this->getInfo($result['id']);
  517. if ($info && !empty($fields)) {
  518. // 分析字段
  519. if (!is_array($fields) && strpos($fields, ',')) {
  520. $fields = explode(',', $fields);
  521. }
  522. foreach ($fields as $val) {
  523. $data[trim($val)] = $info[trim($val)];
  524. }
  525. unset($info);
  526. } else {
  527. $data = $info;
  528. }
  529. }
  530. return $data;
  531. }
  532. /**
  533. * 获取数据表
  534. * @return array 返回结果
  535. * @author zongjl
  536. * @date 2019/5/29
  537. */
  538. public function getTablesList()
  539. {
  540. $tables = [];
  541. $database = strtolower(env('DB_DATABASE'));
  542. $sql = 'SHOW TABLES';
  543. $list = \DB::select($sql);
  544. // 对象转数组
  545. $data = object_array($list);
  546. foreach ($data as $v) {
  547. $tables[] = $v["Tables_in_{$database}"];
  548. }
  549. return $tables;
  550. }
  551. /**
  552. * 检查表是否存在
  553. * @param string $table 数据表名
  554. * @return bool 返回结果:true存在,false不存在
  555. * @author zongjl
  556. * @date 2019/5/29
  557. */
  558. public function tableExists($table)
  559. {
  560. if (strpos($table, DB_PREFIX) === false) {
  561. $table = DB_PREFIX . $table;
  562. }
  563. $tables = $this->getTablesList();
  564. return in_array($table, $tables) ? true : false;
  565. }
  566. /**
  567. * 删除数据表
  568. * @param string $table 数据表名
  569. * @return mixed 结果返回值
  570. * @author zongjl
  571. * @date 2019/5/29
  572. */
  573. public function dropTable($table)
  574. {
  575. if (strpos($table, DB_PREFIX) === false) {
  576. $table = DB_PREFIX . $table;
  577. }
  578. return \DB::statement("DROP TABLE {$table}");
  579. }
  580. /**
  581. * 获取表字段
  582. * @param string $table 数据表名
  583. * @return array 字段数组
  584. * @author zongjl
  585. * @date 2019/5/29
  586. */
  587. public function getFieldsList($table)
  588. {
  589. if (strpos($table, DB_PREFIX) === false) {
  590. $table = DB_PREFIX . $table;
  591. }
  592. $fields = [];
  593. $list = \DB::select("SHOW COLUMNS FROM {$table}");
  594. // 对象转数组
  595. $data = object_array($list);
  596. foreach ($data as $v) {
  597. $fields[$v['Field']] = $v['Type'];
  598. }
  599. return $fields;
  600. }
  601. /**
  602. * 检查字段是否存在
  603. * @param string $table 数据表名
  604. * @param string $field 字段名
  605. * @return bool 返回结果true或false
  606. * @author zongjl
  607. * @date 2019/5/29
  608. */
  609. public function fieldExists($table, $field)
  610. {
  611. $fields = $this->getFieldsList($table);
  612. return array_key_exists($field, $fields);
  613. }
  614. /**
  615. * 插入数据(不存在缓存操作,请慎用)
  616. * @param array $data 数据源
  617. * @param bool $get_id 是否返回插入主键ID:true返回、false不返回
  618. * @return mixed 返回结果
  619. * @author zongjl
  620. * @date 2019/5/29
  621. */
  622. public function doInsert($data, $get_id = true)
  623. {
  624. if ($get_id) {
  625. // 插入数据并返回主键
  626. return $this->insertGetId($data);
  627. } else {
  628. // 返回影响数据的条数,没修改任何数据返回 0
  629. return $this->insert($data);
  630. }
  631. }
  632. /**
  633. * 更新数据(不存在缓存操作,请慎用)
  634. * @param array $data 数据源
  635. * @param array $where 更新条件
  636. * @param bool $is_sql
  637. * @return mixed 返回结果
  638. * @author zongjl
  639. * @date 2019/5/29
  640. */
  641. public function doUpdate($data, $where, $is_sql = false)
  642. {
  643. // 注册打印SQL监听事件
  644. $this->getLastSql($is_sql);
  645. // 闭包查询条件格式化
  646. $query = $this->formatQuery($this, $where);
  647. return $query->update($data);
  648. }
  649. /**
  650. * 删除数据(不存在缓存操作,请慎用)
  651. * @param array $where 查询条件
  652. * @param bool $is_sql 是否打印SQL
  653. * @return mixed 返回结果
  654. * @author zongjl
  655. * @date 2019/5/29
  656. */
  657. public function doDelete($where, $is_sql = false)
  658. {
  659. // 注册打印SQL监听事件
  660. $this->getLastSql($is_sql);
  661. // 闭包查询条件格式化
  662. $query = $this->formatQuery($this, $where);
  663. return $query->delete();
  664. }
  665. /**
  666. * 批量插入数据
  667. * @param array $data 数据源
  668. * @param bool $is_cache 是否设置缓存:true设置,false不设置
  669. * @return bool 返回结果true或false
  670. * @author zongjl
  671. * @date 2019/5/30
  672. */
  673. public function insertAll($data, $is_cache = true)
  674. {
  675. if (!is_array($data)) {
  676. return false;
  677. }
  678. if ($is_cache) {
  679. // 插入数据并设置缓存
  680. $num = 0;
  681. foreach ($data as $val) {
  682. $result = $this->edit($val);
  683. if ($result) {
  684. $num++;
  685. }
  686. }
  687. return $num ? true : false;
  688. } else {
  689. // 插入数据不设置缓存
  690. return $this->insert($data);
  691. }
  692. return false;
  693. }
  694. /**
  695. * 批量更新数据
  696. * @param array $data 数据源(备注,需要更新的数据对象中必须包含有效主键)
  697. * @param bool $is_cache 是否设置缓存:true设置,false不设置
  698. * @return bool 返回结果true或false
  699. * @author zongjl
  700. * @date 2019/5/30
  701. */
  702. public function saveAll($data, $is_cache = true)
  703. {
  704. if (!is_array($data)) {
  705. return false;
  706. }
  707. $num = 0;
  708. foreach ($data as $val) {
  709. if (!isset($val['id']) || empty($val['id'])) {
  710. continue;
  711. }
  712. if ($is_cache) {
  713. // 更新数据并设置缓存
  714. $result = $this->edit($val);
  715. } else {
  716. // 更新数据不设置缓存
  717. $id = $val['id'];
  718. unset($val['id']);
  719. $result = $this->where('id', $id)->update($val);
  720. }
  721. if ($result) {
  722. $num++;
  723. }
  724. }
  725. return $num ? true : false;
  726. }
  727. /**
  728. * 批量删除
  729. * @param array $data 删除记录ID(支持传入数组和逗号分隔ID字符串)
  730. * @param bool $is_force 是否物理删除,true物理删除false软删除
  731. * @return bool 返回结果true或false
  732. * @author zongjl
  733. * @date 2019/5/30
  734. */
  735. public function deleteAll($data, $is_force = false)
  736. {
  737. if (empty($data)) {
  738. return false;
  739. }
  740. if (!is_array($data)) {
  741. $data = explode(',', $data);
  742. }
  743. $num = 0;
  744. foreach ($data as $val) {
  745. if ($is_force) {
  746. // 物理删除
  747. $result = $this->where('id', $val)->delete();
  748. if ($result) {
  749. $this->cacheDelete($val);
  750. }
  751. } else {
  752. // 软删除
  753. $result = $this->drop($val);
  754. }
  755. if ($result) {
  756. $num++;
  757. }
  758. }
  759. return $num ? true : false;
  760. }
  761. /**
  762. * 获取数据列表【根据业务场景需要,封装的获取列表数据的常用方法】
  763. * @param array $map 查询条件
  764. * @param array $sort 排序(默认:id asc)
  765. * @param string $limit 限制条数
  766. * @param bool $is_sql 是否打印SQL
  767. * @return array 返回结果
  768. * @author zongjl
  769. * @date 2019/5/23
  770. */
  771. public function getList($map = [], $sort = [['id', 'asc']], $limit = '', $is_sql = false)
  772. {
  773. // 注册打印SQL监听事件
  774. $this->getLastSql($is_sql);
  775. // 必备查询条件
  776. $map[] = ['mark', '=', 1];
  777. // 闭包查询条件格式化
  778. $query = $this->formatQuery($this, $map);
  779. // 数据分页设置
  780. if ($limit) {
  781. list($offset, $page_size) = explode(',', $limit);
  782. $query = $query->offset($offset)->limit($page_size);
  783. }
  784. // 排序(支持多重排序)
  785. $query = $query->when($sort, function ($query, $sort) {
  786. foreach ($sort as $v) {
  787. $query->orderBy($v[0], $v[1]);
  788. }
  789. });
  790. // 查询数据并将对象转数组
  791. $result = $query->select('id')->get();
  792. $result = $result ? $result->toArray() : [];
  793. $list = [];
  794. if ($result) {
  795. foreach ($result as $val) {
  796. $info = $this->getInfo($val['id']);
  797. if (!$info) {
  798. continue;
  799. }
  800. $list[] = $info;
  801. }
  802. }
  803. return $list;
  804. }
  805. /**
  806. * 获取数据列表
  807. * @return array 返回结果
  808. * @author zongjl
  809. * @date 2019/5/27
  810. */
  811. public function getData()
  812. {
  813. // 获取参数
  814. $arg_list = func_get_args();
  815. // 查询参数
  816. $map = isset($arg_list[0]['query']) ? $arg_list[0]['query'] : [];
  817. // 排序
  818. $sort = isset($arg_list[0]['sort']) ? $arg_list[0]['sort'] : [['id', 'desc']];
  819. // 获取条数
  820. $limit = isset($arg_list[0]['limit']) ? $arg_list[0]['limit'] : '';
  821. // 回调方法名
  822. $func = isset($arg_list[1]) ? $arg_list[1] : "Short";
  823. // 自定义MODEL
  824. $model = isset($arg_list[2]) ? $arg_list[2] : $this;
  825. // 必备查询条件
  826. $map[] = ['mark', '=', 1];
  827. // 闭包查询条件格式化
  828. $query = $this->formatQuery($model, $map);
  829. // 排序(支持多重排序)
  830. $query = $query->when($sort, function ($query, $sort) {
  831. foreach ($sort as $v) {
  832. $query->orderBy($v[0], $v[1]);
  833. }
  834. });
  835. // 查询数据源
  836. if ($limit) {
  837. list($offset, $page_size) = explode(',', $limit);
  838. $query->offset($offset)->limit($page_size);
  839. } else {
  840. // TODO...
  841. }
  842. // 查询数据并转为数组
  843. $result = $query->select('id')->get();
  844. $result = $result ? $result->toArray() : [];
  845. $list = [];
  846. if (is_array($result)) {
  847. foreach ($result as $val) {
  848. $info = $model->getInfo($val['id']);
  849. if (!$info) {
  850. continue;
  851. }
  852. if (is_object($func)) {
  853. // 方法函数
  854. $data = $func($info);
  855. } else {
  856. // 直接返回
  857. $data = $info;
  858. }
  859. $list[] = $data;
  860. }
  861. }
  862. return $list;
  863. }
  864. /**
  865. * 获取数据列表
  866. * @return array 返回结果
  867. * @author zongjl
  868. * @date 2019/5/27
  869. */
  870. public function pageData()
  871. {
  872. // 获取参数
  873. $arg_list = func_get_args();
  874. // 查询参数
  875. $map = isset($arg_list[0]['query']) ? $arg_list[0]['query'] : [];
  876. // 排序
  877. $sort = isset($arg_list[0]['sort']) ? $arg_list[0]['sort'] : [['id', 'desc']];
  878. // 页码
  879. $page = isset($arg_list[0]['page']) ? $arg_list[0]['page'] : 1;
  880. // 每页数
  881. $perpage = isset($arg_list[0]['perpage']) ? $arg_list[0]['perpage'] : 20;
  882. // 回调方法名
  883. $func = isset($arg_list[1]) ? $arg_list[1] : "Short";
  884. // 自定义MODEL
  885. $model = isset($arg_list[2]) ? $arg_list[2] : $this;
  886. // 必备查询条件
  887. $map[] = ['mark', '=', 1];
  888. // 分页设置
  889. $start = ($page - 1) * $perpage;
  890. $limit = "{$start},{$perpage}";
  891. // 闭包查询条件格式化
  892. $query = $this->formatQuery($model, $map);
  893. // 查询总数
  894. $count = $query->count();
  895. // 排序(支持多重排序)
  896. $query = $query->when($sort, function ($query, $sort) {
  897. foreach ($sort as $v) {
  898. $query->orderBy($v[0], $v[1]);
  899. }
  900. });
  901. // 分页设置
  902. list($offset, $page_size) = explode(',', $limit);
  903. $result = $query->offset($offset)->limit($page_size)->select('id')->get();
  904. $result = $result ? $result->toArray() : [];
  905. $list = [];
  906. if (is_array($result)) {
  907. foreach ($result as $val) {
  908. $info = $model->getInfo($val['id']);
  909. if (!$info) {
  910. continue;
  911. }
  912. if (is_object($func)) {
  913. //方法函数
  914. $data = $func($info);
  915. } else {
  916. // 直接返回
  917. $data = $info;
  918. }
  919. $list[] = $data;
  920. }
  921. }
  922. // 返回结果
  923. $result = array(
  924. 'count' => $count,
  925. 'perpage' => $perpage,
  926. 'page' => $page,
  927. 'list' => $list,
  928. );
  929. return $result;
  930. }
  931. /**
  932. * 格式化查询条件
  933. * @param $model 模型
  934. * @param array $map 查询条件
  935. * @return mixed 返回结果
  936. * @author zongjl
  937. * @date 2019/5/30
  938. */
  939. public function formatQuery($model, $map)
  940. {
  941. $query = $model->where(function ($query) use ($map) {
  942. foreach ($map as $v) {
  943. if ($v instanceof \Closure) {
  944. $query = $query->where($v);
  945. continue;
  946. }
  947. // 判断是否是键值对类型
  948. if (key($v) !== 0) {
  949. $key = key($v);
  950. $val = $v[$key];
  951. $v = [$key, is_array($val) ? 'in' : '=', $val];
  952. }
  953. switch ($v[1]) {
  954. case 'like':
  955. // like查询
  956. if (strpos($v[0], '|') !== false) {
  957. $query->where(function ($query) use ($v) {
  958. $item = explode('|', $v[0]);
  959. foreach ($item as $vo) {
  960. $query->orWhere($vo, $v[1], $v[2]);
  961. }
  962. });
  963. } else {
  964. $query->where($v[0], $v[1], $v[2]);
  965. }
  966. break;
  967. case 'in':
  968. // in查询
  969. if (!is_array($v[2])) {
  970. $v[2] = explode(',', $v[2]);
  971. }
  972. $query->whereIn($v[0], $v[2]);
  973. break;
  974. case 'not in':
  975. // not in查询
  976. if (!is_array($v[2])) {
  977. $v[2] = explode(',', $v[2]);
  978. }
  979. $query->whereNotIn($v[0], $v[2]);
  980. break;
  981. case 'between':
  982. // between查询
  983. if (!is_array($v[2])) {
  984. $v[2] = explode(',', $v[2]);
  985. }
  986. $query->whereBetween($v[0], $v[2]);
  987. break;
  988. case 'not between':
  989. // not between查询
  990. if (!is_array($v[2])) {
  991. $v[2] = explode(',', $v[2]);
  992. }
  993. $query->whereNotBetween($v[0], $v[2]);
  994. break;
  995. case 'null':
  996. // null查询
  997. $query->whereNull($v[0]);
  998. break;
  999. case "not null":
  1000. // not null查询
  1001. $query->whereNotNull($v[0]);
  1002. break;
  1003. case "or":
  1004. // or查询
  1005. //格式:or (status=1 and status=2)
  1006. $where = $v[0];
  1007. $query->orWhere(function ($query) use ($where) {
  1008. // 递归解析查询条件
  1009. $this->formatQuery($query, $where);
  1010. });
  1011. break;
  1012. case 'xor':
  1013. // xor查询
  1014. // 格式:and (status=1 or status=2)
  1015. $where = $v[0];
  1016. $query->where(function ($query) use ($where) {
  1017. foreach ($where as $w) {
  1018. $query->orWhere(function ($query) use ($w) {
  1019. // 递归解析查询条件
  1020. $this->formatQuery($query, [$w]);
  1021. });
  1022. }
  1023. });
  1024. break;
  1025. default:
  1026. // 常规查询
  1027. if (count($v) == 2) {
  1028. $query->where($v[0], '=', $v[1]);
  1029. } else {
  1030. $query->where($v[0], $v[1], $v[2]);
  1031. }
  1032. break;
  1033. }
  1034. }
  1035. });
  1036. return $query;
  1037. }
  1038. /**
  1039. * 添加打印SQL语句监听事件
  1040. * @param bool $is_sql 是否打印SQL
  1041. * @author zongjl
  1042. * @date 2019/5/29
  1043. */
  1044. public function getLastSql($is_sql = false)
  1045. {
  1046. if ($is_sql) {
  1047. \DB::listen(function ($query) {
  1048. $bindings = $query->bindings;
  1049. $sql = $query->sql;
  1050. foreach ($bindings as $replace) {
  1051. $value = is_numeric($replace) ? $replace : "'" . $replace . "'";
  1052. $sql = preg_replace('/\?/', $value, $sql, 1);
  1053. }
  1054. echo $sql;
  1055. });
  1056. }
  1057. }
  1058. /**
  1059. * 开启事务
  1060. * @author zongjl
  1061. * @date 2019/5/30
  1062. */
  1063. public function startTrans()
  1064. {
  1065. // 事务-缓存相关处理
  1066. $GLOBALS['trans'] = true;
  1067. $transId = uniqid("trans_");
  1068. $GLOBALS['trans_id'] = $transId;
  1069. $GLOBALS['trans_keys'] = [];
  1070. $info = debug_backtrace();
  1071. $this->setCache($transId, $info[0]);
  1072. // 开启事务
  1073. \DB::beginTransaction();
  1074. }
  1075. /**
  1076. * 事务回滚
  1077. * @author zongjl
  1078. * @date 2019/5/30
  1079. */
  1080. public function rollBack()
  1081. {
  1082. // 事务回滚
  1083. \DB::rollBack();
  1084. // 回滚缓存处理
  1085. foreach ($GLOBALS['trans_keys'] as $key) {
  1086. $this->deleteCache($key);
  1087. }
  1088. $this->deleteCache($GLOBALS['trans_id']);
  1089. $GLOBALS['trans'] = false;
  1090. $GLOBALS['trans_keys'] = [];
  1091. }
  1092. /**
  1093. * 提交事务
  1094. * @author zongjl
  1095. * @date 2019/5/30
  1096. */
  1097. public function commit()
  1098. {
  1099. // 提交事务
  1100. \DB::commit();
  1101. // 事务缓存同步删除
  1102. $GLOBALS['trans'] = false;
  1103. $GLOBALS['trans_keys'] = [];
  1104. $this->deleteCache($GLOBALS['trans_id']);
  1105. }
  1106. /**
  1107. * 开启执行日志
  1108. * @author zongjl
  1109. * @date 2019/5/31
  1110. */
  1111. public function beginSQLLog()
  1112. {
  1113. \DB::connection()->enableQueryLog();
  1114. }
  1115. /**
  1116. * 结束日志并打印
  1117. * @author zongjl
  1118. * @date 2019/5/30
  1119. */
  1120. public function endSQLLog()
  1121. {
  1122. // 获取查询语句、参数和执行时间
  1123. $result = \DB::getLastSql();
  1124. if ($result) {
  1125. foreach ($result as &$val) {
  1126. $bindings = $val['bindings'];
  1127. $sql = $val['query'];
  1128. foreach ($bindings as $replace) {
  1129. $value = is_numeric($replace) ? $replace : "'" . $replace . "'";
  1130. $val['query'] = preg_replace('/\?/', $value, $sql, 1);
  1131. }
  1132. }
  1133. }
  1134. print_r($result);
  1135. exit;
  1136. }
  1137. }