RequestCriteria.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. /*
  3. * This file is part of the Jiannei/lumen-api-starter.
  4. *
  5. * (c) Jiannei <longjian.huang@foxmail.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace App\Repositories\Criteria;
  11. use Illuminate\Database\Eloquent\Builder;
  12. use Illuminate\Database\Eloquent\Model;
  13. use Illuminate\Support\Str;
  14. use Prettus\Repository\Contracts\RepositoryInterface;
  15. use Prettus\Repository\Criteria\RequestCriteria as BaseRequestCriteria;
  16. class RequestCriteria extends BaseRequestCriteria
  17. {
  18. /**
  19. * Apply criteria in query repository.
  20. *
  21. * @param Builder|Model $model
  22. * @param RepositoryInterface $repository
  23. * @return mixed
  24. *
  25. * @throws \Exception
  26. */
  27. public function apply($model, RepositoryInterface $repository)
  28. {
  29. $cursor = $this->request->get(config('repository.criteria.params.cursor', 'cursor'));
  30. if ($cursor) {
  31. $keyType = $model->getKeyType();
  32. $key = $model->getKeyName();
  33. $cursor = in_array($keyType, ['int', 'integer']) ? (int)$cursor : $cursor;
  34. $sortedBy = $this->request->get(config('repository.criteria.params.sortedBy', 'sortedBy'), 'asc');
  35. $sortedBy = !empty($sortedBy) ? Str::lower($sortedBy) : 'asc';
  36. $model = ($sortedBy === 'asc') ? $model->where($key, '>', $cursor) : $model->where($key, '<', $cursor);
  37. }
  38. return parent::apply($model, $repository);
  39. }
  40. }