RequestCriteria.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. *
  24. * @return mixed
  25. * @throws \Exception
  26. */
  27. public function apply($model, RepositoryInterface $repository)
  28. {
  29. $sortedBy = $this->request->get(config('repository.criteria.params.sortedBy', 'sortedBy'), 'asc');
  30. $cursor = $this->request->get(config('repository.criteria.params.cursor', 'cursor'), null);
  31. $sortedBy = ! empty($sortedBy) ? Str::lower($sortedBy) : 'asc';
  32. if ($cursor) {
  33. $keyType = $model->getKeyType();
  34. $key = $model->getKeyName();
  35. $cursor = in_array($keyType, ['int', 'integer']) ? (int) $cursor : $cursor;
  36. $model = ($sortedBy === 'asc') ? $model->where($key, '>', $cursor) : $model->where($key, '<', $cursor);
  37. }
  38. return parent::apply($model, $repository);
  39. }
  40. }