CommonService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Pagination\LengthAwarePaginator;
  5. use Illuminate\Support\Facades\DB;
  6. use App\Exceptions\ApiException;
  7. use App\Models\BaseModel;
  8. use Illuminate\Support\Collection;
  9. use Illuminate\Support\Facades\Cache;
  10. /**
  11. * 用于后台管理员用户
  12. * */
  13. abstract class CommonService
  14. {
  15. use CacheTrait;
  16. /**
  17. * BaseModel
  18. * @var BaseModel
  19. */
  20. protected $model;
  21. /**
  22. * 是否缓存数据
  23. * @var bool
  24. */
  25. protected $cache = false;
  26. /**
  27. * 缓存空间
  28. * @var string
  29. */
  30. protected $cacheBucket = '';
  31. /**
  32. * CommonBaseService constructor.
  33. * @param BaseModel $model
  34. */
  35. public function __construct(BaseModel $model)
  36. {
  37. $this->model = $model;
  38. }
  39. /**
  40. * 获取url地址
  41. *
  42. * @return string http://lumen.lwj_house.cn
  43. */
  44. public function getBaseUrl()
  45. {
  46. return app()->make(Request::class)->root();
  47. }
  48. /**
  49. * 缓存key
  50. * @param $id
  51. * @return string
  52. */
  53. protected function getCacheId($id)
  54. {
  55. return $this->cacheBucket . '-' . md5($id);
  56. }
  57. /**
  58. * 获取绑定的model
  59. * @return BaseModel
  60. */
  61. public function getModel()
  62. {
  63. return $this->model;
  64. }
  65. /**
  66. * 开启事务
  67. */
  68. public function beginTransaction()
  69. {
  70. $this->model->getConnection()->beginTransaction();
  71. }
  72. /**
  73. * 提交事务
  74. */
  75. public function commit()
  76. {
  77. $this->model->getConnection()->commit();
  78. }
  79. /**
  80. * 回滚事务
  81. */
  82. public function rollback()
  83. {
  84. $this->model->getConnection()->rollBack();
  85. }
  86. /**
  87. * 保存数据
  88. * @param $data
  89. * @return BaseModel
  90. */
  91. public function save($data)
  92. {
  93. $this->model = $this->model->newInstance();
  94. $data = $this->model->filter($data);
  95. foreach ($data as $key => $item) {
  96. $this->model->$key = $item;
  97. }
  98. $this->model->save();
  99. return $this->model;
  100. }
  101. /**
  102. * 批量保存数据
  103. * @param $data
  104. */
  105. public function saveAll($data)
  106. {
  107. if (empty($data)) {
  108. return;
  109. }
  110. //过滤字段数据
  111. foreach ($data as &$item) {
  112. $item = $this->model->filter($item);
  113. }
  114. //批量插入
  115. $this->model->newInstance()->getConnection()->table($this->model->getTable())->insert($data);
  116. }
  117. /**
  118. * 根据主键判断保存或者更新
  119. * @param $data
  120. * @return BaseModel
  121. */
  122. public function saveOrUpdate($data)
  123. {
  124. $key = $this->model->getKeyName();
  125. if (isset($data[$key]) && !empty($data[$key])) {
  126. return $this->update($data[$key], $data);
  127. } else {
  128. return $this->save($data);
  129. }
  130. }
  131. /**
  132. * 详情
  133. * @param $id
  134. * @return BaseModel
  135. */
  136. public function show($id)
  137. {
  138. return $this->findOneById($id);
  139. }
  140. /**
  141. * 更新数据
  142. * @param int $id
  143. * @param array $data 更新数据
  144. * @return BaseModel
  145. */
  146. public function update($id, array $data)
  147. {
  148. if ($this->cache) {
  149. Cache::forget($this->getCacheId($id));
  150. }
  151. if (method_exists($this->model, 'runSoftDelete')) {
  152. $model = $this->model->whereKey($id)->withAll()->first();
  153. } else {
  154. $model = $this->model->whereKey($id)->first();
  155. }
  156. //被删除的记录 抛出异常
  157. if (empty($model)) {
  158. throw new ApiException(1009);
  159. }
  160. $data = $this->model->filter($data);
  161. foreach ($data as $key => $item) {
  162. $model->$key = $item;
  163. }
  164. $model->save();
  165. return $model;
  166. }
  167. /**
  168. * 根据多个条件更新数据
  169. * @param array $criteria
  170. * @param array $data
  171. * @return bool
  172. */
  173. public function updateBy($criteria, array $data)
  174. {
  175. if ($this->cache) {
  176. if (method_exists($this->model, 'runSoftDelete')) {
  177. $list = $this->model->newInstance()->buildQuery($criteria)->withAll()->get();
  178. } else {
  179. $list = $this->model->newInstance()->buildQuery($criteria)->get();
  180. }
  181. foreach ($list as $item) {
  182. Cache::forget($this->getCacheId($item[$this->model->getKeyName()]));
  183. }
  184. }
  185. $data = $this->model->filter($data);
  186. if (method_exists($this->model, 'runSoftDelete')) {
  187. $res = $this->model->newInstance()->buildQuery($criteria)->withAll()->update($data);
  188. } else {
  189. $res = $this->model->newInstance()->buildQuery($criteria)->update($data);
  190. }
  191. return $res;
  192. }
  193. /**
  194. * 列表查询
  195. * @param $data
  196. * @return Collection
  197. */
  198. public function index($data)
  199. {
  200. return $this->model->whereRaw($this->getCondition($data))->paginate($this->getPageSize($data));
  201. }
  202. /**
  203. * 获取查询条件
  204. * @param $data
  205. * @return string
  206. */
  207. protected function getCondition($data)
  208. {
  209. if (!is_array($data)) {
  210. return '';
  211. }
  212. $data = $this->model->filter($data);
  213. $condition = '1=1';
  214. foreach ($data as $key => $item) {
  215. $condition .= " and " . $key . "='" . $item . "'";
  216. }
  217. return $condition;
  218. }
  219. /**
  220. * 获取分页行数
  221. * @param $data
  222. * @return int
  223. */
  224. protected function getPageSize($data)
  225. {
  226. return $data['page_size'] ?? config('app.app_rows');
  227. }
  228. /**
  229. * 删除数据
  230. * @param $id int|array
  231. * @return bool|null
  232. */
  233. public function delete($id)
  234. {
  235. if (is_array($id)) {
  236. return $this->deleteBy([
  237. $this->model->getKeyName() => [
  238. ['in', $id]
  239. ]
  240. ]);
  241. } else {
  242. return $this->deleteBy([
  243. $this->model->getKeyName() => $id
  244. ]);
  245. }
  246. }
  247. /**
  248. * 根据条件删除数据
  249. * @param $criteria
  250. * @return bool|null
  251. */
  252. public function deleteBy($criteria)
  253. {
  254. if (method_exists($this->model, 'runSoftDelete')) {
  255. $res = $this->model->newInstance()->buildQuery($criteria)->withAll()->get();
  256. } else {
  257. $res = $this->model->newInstance()->buildQuery($criteria)->get();
  258. }
  259. if ($this->cache) {
  260. foreach ($res as $item) {
  261. Cache::forget($this->getCacheId($item[$this->model->getKeyName()]));
  262. }
  263. }
  264. if (method_exists($this->model, 'runSoftDelete')) {
  265. return $this->model->newInstance()->buildQuery($criteria)->withAll()->delete();
  266. } else {
  267. //系统所有删除均为软删除
  268. if(!empty($this->model::DELETED_AT)){
  269. $data=[];
  270. $data[$this->model::DELETED_AT]=$this->model::STATUS_DELETED;
  271. return $this->model->newInstance()->buildQuery($criteria)->update($data);
  272. }else{
  273. return $this->model->newInstance()->buildQuery($criteria)->delete();
  274. }
  275. }
  276. }
  277. /**
  278. * 根据条件恢复数据
  279. * @param $criteria
  280. * @return bool|null
  281. */
  282. public function restoreBy($criteria)
  283. {
  284. $res = $this->model->newInstance()->buildQuery($criteria)->get();
  285. if ($this->cache) {
  286. foreach ($res as $item) {
  287. Cache::forget($this->getCacheId($item[$this->model->getKeyName()]));
  288. }
  289. }
  290. return $this->model->newInstance()->buildQuery($criteria)->restore();
  291. }
  292. /**
  293. * 启用
  294. * @param $id
  295. * @return bool|null
  296. */
  297. public function enabled($id)
  298. {
  299. if ($this->cache) {
  300. Cache::forget($this->getCacheId($id));
  301. }
  302. $model = $this->model->newInstance();
  303. return $model->whereKey($id)->restore();
  304. }
  305. /**
  306. * 禁用
  307. * @param $id
  308. * @return mixed
  309. */
  310. public function disabled($id)
  311. {
  312. if ($this->cache) {
  313. Cache::forget($this->getCacheId($id));
  314. }
  315. $model = $this->model->newInstance();
  316. return $model->whereKey($id)->update(['status' => $model::STATUS_DISABLED]);
  317. }
  318. /**
  319. * id获取详情
  320. * @param $id
  321. * @return BaseModel
  322. */
  323. public function findOneById($id, $fields = '*')
  324. {
  325. $model = $this->model->newInstance();
  326. if ($this->cache && $fields == '*') {
  327. $info = Cache::remember($this->getCacheId($id), config('cache.time'), function () use ($model, $id, $fields) {
  328. if (method_exists($model, 'runSoftDelete')) {
  329. return $model->whereKey($id)->withAll()->select(DB::raw($fields))->first();
  330. } else {
  331. return $model->whereKey($id)->select(DB::raw($fields))->first();
  332. }
  333. });
  334. } else {
  335. if (method_exists($model, 'runSoftDelete')) {
  336. $info = $model->whereKey($id)->withAll()->selectRaw($fields)->first();
  337. } else {
  338. $info = $model->whereKey($id)->select(DB::raw($fields))->first();
  339. }
  340. }
  341. return $info;
  342. }
  343. /**
  344. * 查找数据
  345. * @param array|string $criteria
  346. * @return BaseModel
  347. */
  348. public function findOneBy($criteria, $fields = '*')
  349. {
  350. return $this->model->newInstance()->buildQuery($criteria)->select(DB::raw($fields))->first();
  351. }
  352. /**
  353. * 查找数据
  354. * @param array|string $criteria
  355. * @return Collection
  356. */
  357. public function findBy($criteria, $fields = '*')
  358. {
  359. return $this->model->newInstance()->buildQuery($criteria)->select(DB::raw($fields))->get();
  360. }
  361. /**
  362. * 查询符合条件的行数
  363. * @param $criteria
  364. * @return int
  365. */
  366. public function count($criteria)
  367. {
  368. return $this->model->newInstance()->buildQuery($criteria)->count();
  369. }
  370. /**
  371. * sql原生查询
  372. * @param $sql
  373. * @return array
  374. */
  375. public function query($sql)
  376. {
  377. $data = $this->model->getConnection()->select($sql);
  378. return json_decode(json_encode($data), true);
  379. }
  380. /**
  381. * 字段唯一性性验证
  382. * 修改数据验证时请组装主键notIn条件语句,返回false时为存在重复
  383. * @param $field
  384. * @param $value
  385. * @param $criteria
  386. * @return bool
  387. */
  388. public function checkFieldUnique($field, $value, $criteria)
  389. {
  390. $collection = $this->model->newInstance()->buildQuery($criteria)->selectRaw($field)->get();
  391. if (empty($collection->toArray())) {
  392. return true;
  393. }
  394. $checkArray = array_column($collection->toArray(), $field);
  395. if (in_array($value, $checkArray)) {
  396. return false;
  397. }
  398. return true;
  399. }
  400. /**
  401. * Increment a column's value by a given amount.
  402. * @param $criteria
  403. * @param $column
  404. * @param int $amount
  405. * @param array $extra
  406. * @return int
  407. */
  408. public function incrementBy($criteria, $column, $amount = 1, array $extra = [])
  409. {
  410. return $this->model->newInstance()->buildQuery($criteria)->increment($column, $amount, $extra);
  411. }
  412. /**
  413. * Decrement a column's value by a given amount.
  414. * @param $criteria
  415. * @param $column
  416. * @param int $amount
  417. * @param array $extra
  418. * @return int
  419. */
  420. public function decrementBy($criteria, $column, $amount = 1, array $extra = [])
  421. {
  422. return $this->model->newInstance()->buildQuery($criteria)->decrement($column, $amount, $extra);
  423. }
  424. /**
  425. * 获取某一字段值
  426. * @param $field
  427. * @param $criteria
  428. * @return string|int|array
  429. */
  430. public function getFieldBy($field, $criteria)
  431. {
  432. $findOne = $this->findOneBy($criteria, $field);
  433. $findOne = $findOne ? $findOne->toArray() : [];
  434. return $findOne[$field] ?? '';
  435. }
  436. /**
  437. * 根据id获取某一个字段值
  438. * @param $field
  439. * @param $id
  440. * @return array|int|string
  441. */
  442. public function getFieldById($field, $id)
  443. {
  444. return $this->getFieldBy($field, [
  445. $this->model->getKeyName() => $id
  446. ]);
  447. }
  448. /**
  449. * 获取模型的table
  450. * @return string
  451. */
  452. public function getTable()
  453. {
  454. return $this->model->getTable();
  455. }
  456. /**
  457. * 分页
  458. * @param $items 数据结果集
  459. * @param $total 总数量
  460. * @return LengthAwarePaginator
  461. */
  462. public function paginator($items, $total)
  463. {
  464. $request = app()->make(Request::class);
  465. $params = $request->all();
  466. if (isset($params['page'])) unset($params['page']);
  467. $path = $request->url();
  468. $perPage = $this->getPageSize($params);
  469. $options = [
  470. 'path' => $path,
  471. 'query' => $params,
  472. ];
  473. $page = new LengthAwarePaginator($items, $total, $perPage, $currentPage = null, $options);
  474. return $page;
  475. }
  476. /**
  477. * 通用缓存方法
  478. * @param string $key
  479. * @param array $data
  480. * */
  481. public function setCacheData($key, $data,$cacheTime=0)
  482. {
  483. $cacheTime=empty($cacheTime)?config('cache.def_time'):$cacheTime;
  484. Cache::put($this->getCacheKey($key), $data, $cacheTime);
  485. }
  486. /**
  487. * 通用缓存方法
  488. * @param string $key
  489. * @param array $data
  490. * */
  491. public function getCacheData($key)
  492. {
  493. $dataKey= $this->getCacheKey($key);
  494. return Cache::get($dataKey);
  495. }
  496. public function getCacheKeysAll($key)
  497. {
  498. return $this->getCacheClient()->keys('*' . $key . '*');
  499. }
  500. /**
  501. * 模糊清除所有前缀的缓存
  502. * @param $key
  503. */
  504. public function removeByKey($key)
  505. {
  506. $list = $this->getCacheKeysAll($key);
  507. foreach($list as $item){
  508. $this->getCacheClient()->del($item);
  509. }
  510. }
  511. /**
  512. * 获取通用缓存数据key
  513. * @param string $key
  514. * @return string
  515. * */
  516. private function getCacheKey($key)
  517. {
  518. return $this->cacheBucket.$key;
  519. }
  520. }