Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Ooga\Eloquent\Traits;
  4.  
  5. use Illuminate\Contracts\Pagination\LengthAwarePaginator;
  6. use Illuminate\Database\Eloquent\Builder;
  7. use Illuminate\Pagination\AbstractPaginator;
  8. use Illuminate\Pagination\Paginator;
  9. use InvalidArgumentException;
  10.  
  11. /**
  12. * distinct句を使用する場合のページネータ
  13. * @package Ooga\Eloquent\Traits
  14. *
  15. * @method @method AbstractPaginator|LengthAwarePaginator distinctPaginate(int $perPage = null, array $columns = ['*'], string $pageName = 'page', $page = null)
  16. */
  17. trait DistinctPaginator
  18. {
  19. /**
  20. * Boot the DistinctPaginator trait for a model.
  21. *
  22. * @return void
  23. * @throws InvalidArgumentException
  24. */
  25. public static function bootDistinctPaginator(): void
  26. {
  27. /**
  28. * ページネーターにdistinctを使えるようにするためのmacro
  29. * デフォルトのページネータだとtotalの取得がdistinctに対応してくれないので、件数がずれる
  30. *
  31. * このメソッドの制約事項としては、distinctに掛けるカラムを第1引数に捕る(*の指定は落ちるので不可)
  32. * qualifier.column_nameで指定すること推奨
  33. */
  34. Builder::macro('distinctPaginate', function ($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) {
  35. $page = $page ?: Paginator::resolveCurrentPage($pageName);
  36.  
  37. $perPage = $perPage ?: $this->model->getPerPage();
  38.  
  39. if ($this->query->distinct) {
  40. $results = ($total = $this->toBase()->getCountForPagination([$columns[0]]))
  41. ? $this->forPage($page, $perPage)->get($columns)
  42. : $this->model->newCollection();
  43. } else {
  44. $results = ($total = $this->toBase()->getCountForPagination())
  45. ? $this->forPage($page, $perPage)->get($columns)
  46. : $this->model->newCollection();
  47. }
  48.  
  49. return $this->paginator($results, $total, $perPage, $page, [
  50. 'path' => Paginator::resolveCurrentPath(),
  51. 'pageName' => $pageName,
  52. ]);
  53. });
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement