SearchDaoTrait.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\traits;
  12. use app\dao\BaseDao;
  13. use crmeb\basic\BaseAuth;
  14. /**
  15. * Trait SearchDaoTrait
  16. * @package crmeb\traits
  17. * @mixin BaseDao
  18. */
  19. trait SearchDaoTrait
  20. {
  21. /**
  22. * 搜索(没有进入搜索器的自动进入where条件)
  23. * @param array $where
  24. * @param bool $authWhere
  25. * @return \crmeb\basic\BaseModel
  26. */
  27. public function searchWhere(array $where, bool $authWhere = true)
  28. {
  29. [$with, $whereKey] = app()->make(BaseAuth::class)->________(array_keys($where), $this->setModel());
  30. $whereData = [];
  31. foreach ($whereKey as $key) {
  32. if (isset($where[$key]) && 'timeKey' !== $key) {
  33. $whereData[$key] = $where[$key];
  34. }
  35. }
  36. return $this->getModel()->withSearch($with, $where)->when($authWhere && $whereData, function ($query) use ($whereData) {
  37. $query->where($whereData);
  38. });
  39. }
  40. /**
  41. * @param array $where
  42. * @param bool $authWhere
  43. * @return int
  44. */
  45. public function count(array $where = [], bool $authWhere = true): int
  46. {
  47. return $this->searchWhere($where, $authWhere)->count();
  48. }
  49. /**
  50. * 搜索
  51. * @param array $where
  52. * @param array|string[] $field
  53. * @param int $page
  54. * @param int $limit
  55. * @param null $sort
  56. * @param array $with
  57. * @return array
  58. */
  59. public function getDataList(array $where, array $field = ['*'], int $page = 0, int $limit = 0, $sort = null, array $with = [])
  60. {
  61. return $this->searchWhere($where)->when($page && $limit, function ($query) use ($page, $limit) {
  62. $query->page($page, $limit);
  63. })->when(!$page && $limit, function ($query) use ($limit) {
  64. $query->limit($limit);
  65. })->when($sort, function ($query, $sort) {
  66. if (is_array($sort)) {
  67. foreach ($sort as $k => $v) {
  68. if (is_numeric($k)) {
  69. $query->order($v, 'desc');
  70. } else {
  71. $query->order($k, $v);
  72. }
  73. }
  74. } else {
  75. $query->order($sort, 'desc');
  76. }
  77. })->field($field)->with($with)->select()->toArray();
  78. }
  79. }