QueryBuilderRepository.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. <?php
  2. namespace Dcat\Admin\Repositories;
  3. use Dcat\Admin\Contracts\TreeRepository;
  4. use Dcat\Admin\Exception\RuntimeException;
  5. use Dcat\Admin\Form;
  6. use Dcat\Admin\Grid;
  7. use Dcat\Admin\Show;
  8. use Illuminate\Database\Eloquent\Builder;
  9. use Illuminate\Support\Collection;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Str;
  12. class QueryBuilderRepository extends Repository implements TreeRepository
  13. {
  14. /**
  15. * @var string
  16. */
  17. protected $table;
  18. /**
  19. * @var string
  20. */
  21. protected $connection;
  22. /**
  23. * @var string
  24. */
  25. protected $createdAtColumn = 'created_at';
  26. /**
  27. * @var string
  28. */
  29. protected $updatedAtColumn = 'updated_at';
  30. /**
  31. * @var Builder
  32. */
  33. protected $queryBuilder;
  34. /**
  35. * QueryBuilderRepository constructor.
  36. */
  37. public function __construct()
  38. {
  39. $this->initQueryBuilder();
  40. }
  41. /**
  42. * 初始化.
  43. */
  44. protected function initQueryBuilder()
  45. {
  46. $this->queryBuilder = $this->connection
  47. ? DB::connection($this->connection)->table($this->getTable())
  48. : DB::table($this->getTable());
  49. }
  50. /**
  51. * @return string
  52. */
  53. public function getTable()
  54. {
  55. return $this->table;
  56. }
  57. /**
  58. * @return string
  59. */
  60. public function getCreatedAtColumn()
  61. {
  62. return $this->createdAtColumn;
  63. }
  64. /**
  65. * @return string
  66. */
  67. public function getUpdatedAtColumn()
  68. {
  69. return $this->updatedAtColumn;
  70. }
  71. /**
  72. * 获取列表页面查询的字段.
  73. *
  74. * @return array
  75. */
  76. public function getGridColumns()
  77. {
  78. return ['*'];
  79. }
  80. /**
  81. * 获取表单页面查询的字段.
  82. *
  83. * @return array
  84. */
  85. public function getFormColumns()
  86. {
  87. return ['*'];
  88. }
  89. /**
  90. * 获取详情页面查询的字段.
  91. *
  92. * @return array
  93. */
  94. public function getDetailColumns()
  95. {
  96. return ['*'];
  97. }
  98. /**
  99. * 查询Grid表格数据.
  100. *
  101. * @param Grid\Model $model
  102. *
  103. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|Collection|array
  104. */
  105. public function get(Grid\Model $model)
  106. {
  107. $this->setSort($model);
  108. $this->setPaginate($model);
  109. $query = $this->newQuery();
  110. $model->getQueries()->unique()->each(function ($value) use (&$query) {
  111. if ($value['method'] == 'paginate') {
  112. $value['arguments'][1] = $this->getGridColumns();
  113. } elseif ($value['method'] == 'get') {
  114. $value['arguments'] = [$this->getGridColumns()];
  115. }
  116. $query = call_user_func_array([$query, $value['method']], $value['arguments'] ?? []);
  117. });
  118. return $query;
  119. }
  120. /**
  121. * 设置表格数据排序.
  122. *
  123. * @param Grid\Model $model
  124. *
  125. * @return void
  126. */
  127. protected function setSort(Grid\Model $model)
  128. {
  129. [$column, $type] = $model->getSort();
  130. if (empty($column) || empty($type)) {
  131. return;
  132. }
  133. if (Str::contains($column, '.')) {
  134. $this->setRelationSort($model, $column, $type);
  135. } else {
  136. $model->resetOrderBy();
  137. $model->addQuery('orderBy', [$column, $type]);
  138. }
  139. }
  140. /**
  141. * 设置关联数据排序.
  142. *
  143. * @param Grid\Model $model
  144. * @param string $column
  145. * @param string $type
  146. *
  147. * @return void
  148. */
  149. protected function setRelationSort(Grid\Model $model, $column, $type)
  150. {
  151. [$relationName, $relationColumn] = explode('.', $column);
  152. if ($model->getQueries()->contains(function ($query) use ($relationName) {
  153. return $query['method'] == 'with' && in_array($relationName, $query['arguments']);
  154. })) {
  155. $model->addQuery('select', [$this->getGridColumns()]);
  156. $model->resetOrderBy();
  157. $model->addQuery('orderBy', [
  158. $relationColumn,
  159. $type,
  160. ]);
  161. }
  162. }
  163. /**
  164. * 设置分页参数.
  165. *
  166. * @param Grid\Model $model
  167. *
  168. * @return void
  169. */
  170. protected function setPaginate(Grid\Model $model)
  171. {
  172. $paginate = $model->findQueryByMethod('paginate');
  173. $model->rejectQuery(['paginate']);
  174. if (! $model->allowPagination()) {
  175. $model->addQuery('get', [$this->getGridColumns()]);
  176. } else {
  177. $model->addQuery('paginate', $this->resolvePerPage($model, $paginate));
  178. }
  179. }
  180. /**
  181. * 获取分页参数.
  182. *
  183. * @param Grid\Model $model
  184. * @param array|null $paginate
  185. *
  186. * @return array
  187. */
  188. protected function resolvePerPage(Grid\Model $model, $paginate)
  189. {
  190. if ($paginate && is_array($paginate)) {
  191. if ($perPage = request()->input($model->getPerPageName())) {
  192. $paginate['arguments'][0] = (int) $perPage;
  193. }
  194. return $paginate['arguments'];
  195. }
  196. return [
  197. $model->getPerPage(),
  198. $this->getGridColumns(),
  199. $model->getPageName(),
  200. $model->getCurrentPage(),
  201. ];
  202. }
  203. /**
  204. * 查询编辑页面数据.
  205. *
  206. * @param Form $form
  207. *
  208. * @return array
  209. */
  210. public function edit(Form $form): array
  211. {
  212. $result = $this->newQuery()
  213. ->where($this->getKeyName(), $form->getKey())
  214. ->first($this->getFormColumns());
  215. if (! $result) {
  216. abort(404);
  217. }
  218. return (array) $result;
  219. }
  220. /**
  221. * 查询详情页面数据.
  222. *
  223. * @param Show $show
  224. *
  225. * @return array
  226. */
  227. public function detail(Show $show): array
  228. {
  229. $result = $this->newQuery()
  230. ->where($this->getKeyName(), $show->getKey())
  231. ->first($this->getDetailColumns());
  232. if (! $result) {
  233. abort(404);
  234. }
  235. return (array) $result;
  236. }
  237. /**
  238. * 新增记录.
  239. *
  240. * @param Form $form
  241. *
  242. * @return mixed
  243. */
  244. public function store(Form $form)
  245. {
  246. $result = null;
  247. DB::transaction(function () use ($form, &$result) {
  248. $result = $this->newQuery()
  249. ->insertGetId($form->updates());
  250. });
  251. return $result;
  252. }
  253. /**
  254. * 查询更新前的行数据.
  255. *
  256. * @param Form $form
  257. *
  258. * @return array
  259. */
  260. public function updating(Form $form): array
  261. {
  262. return $this->edit($form);
  263. }
  264. /**
  265. * 更新数据.
  266. *
  267. * @param Form $form
  268. *
  269. * @return bool
  270. */
  271. public function update(Form $form)
  272. {
  273. $result = null;
  274. DB::transaction(function () use ($form, &$result) {
  275. $result = $this->newQuery()
  276. ->where($this->getKeyName(), $form->getKey())
  277. ->limit(1)
  278. ->update($form->updates());
  279. });
  280. return $result;
  281. }
  282. /**
  283. * 数据行排序上移一个单位.
  284. *
  285. * @return bool
  286. */
  287. public function moveOrderUp()
  288. {
  289. throw new RuntimeException('Not support.');
  290. }
  291. /**
  292. * 数据行排序下移一个单位.
  293. *
  294. * @return bool
  295. */
  296. public function moveOrderDown()
  297. {
  298. throw new RuntimeException('Not support.');
  299. }
  300. /**
  301. * 删除数据.
  302. *
  303. * @param Form $form
  304. *
  305. * @return bool
  306. */
  307. public function delete(Form $form, array $deletingData)
  308. {
  309. $id = $form->getKey();
  310. $deletingData = collect($deletingData)->keyBy($this->getKeyName());
  311. collect(explode(',', $id))->filter()->each(function ($id) use ($form, $deletingData) {
  312. $data = $deletingData->get($id, []);
  313. if (! $data) {
  314. return;
  315. }
  316. $form->deleteFiles($data);
  317. $this->newQuery()
  318. ->where($this->getKeyName(), $id)
  319. ->limit(1)
  320. ->delete();
  321. });
  322. return true;
  323. }
  324. /**
  325. * 查询删除前的行数据.
  326. *
  327. * @param Form $form
  328. *
  329. * @return array
  330. */
  331. public function deleting(Form $form): array
  332. {
  333. $query = $this->newQuery();
  334. $id = $form->getKey();
  335. return $query
  336. ->whereIn(
  337. $this->getKeyName(),
  338. collect(explode(',', $id))->filter()->toArray()
  339. )
  340. ->get($this->getFormColumns())
  341. ->transform(function ($value) {
  342. return (array) $value;
  343. })
  344. ->toArray();
  345. }
  346. /**
  347. * 获取父级ID字段名称.
  348. *
  349. * @return string
  350. */
  351. public function getParentColumn()
  352. {
  353. throw new RuntimeException('Not support.');
  354. }
  355. /**
  356. * 获取标题字段名称.
  357. *
  358. * @return string
  359. */
  360. public function getTitleColumn()
  361. {
  362. throw new RuntimeException('Not support.');
  363. }
  364. /**
  365. * 获取排序字段名称.
  366. *
  367. * @return string
  368. */
  369. public function getOrderColumn()
  370. {
  371. throw new RuntimeException('Not support.');
  372. }
  373. /**
  374. * 保存层级数据排序.
  375. *
  376. * @param array $tree
  377. * @param int $parentId
  378. */
  379. public function saveOrder($tree = [], $parentId = 0)
  380. {
  381. throw new RuntimeException('Not support.');
  382. }
  383. /**
  384. * 设置数据查询回调.
  385. *
  386. * @param \Closure|null $query
  387. *
  388. * @return $this
  389. */
  390. public function withQuery($queryCallback)
  391. {
  392. throw new RuntimeException('Not support.');
  393. }
  394. /**
  395. * 获取层级数据.
  396. *
  397. * @return array
  398. */
  399. public function toTree()
  400. {
  401. throw new RuntimeException('Not support.');
  402. }
  403. /**
  404. * @return Builder
  405. */
  406. protected function newQuery()
  407. {
  408. return clone $this->queryBuilder;
  409. }
  410. }