Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Ooga\Eloquent\Traits;
- use Illuminate\Contracts\Pagination\LengthAwarePaginator;
- use Illuminate\Database\Eloquent\Builder;
- use Illuminate\Pagination\AbstractPaginator;
- use Illuminate\Pagination\Paginator;
- use InvalidArgumentException;
- /**
- * distinct句を使用する場合のページネータ
- * @package Ooga\Eloquent\Traits
- *
- * @method @method AbstractPaginator|LengthAwarePaginator distinctPaginate(int $perPage = null, array $columns = ['*'], string $pageName = 'page', $page = null)
- */
- trait DistinctPaginator
- {
- /**
- * Boot the DistinctPaginator trait for a model.
- *
- * @return void
- * @throws InvalidArgumentException
- */
- public static function bootDistinctPaginator(): void
- {
- /**
- * ページネーターにdistinctを使えるようにするためのmacro
- * デフォルトのページネータだとtotalの取得がdistinctに対応してくれないので、件数がずれる
- *
- * このメソッドの制約事項としては、distinctに掛けるカラムを第1引数に捕る(*の指定は落ちるので不可)
- * qualifier.column_nameで指定すること推奨
- */
- Builder::macro('distinctPaginate', function ($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) {
- $page = $page ?: Paginator::resolveCurrentPage($pageName);
- $perPage = $perPage ?: $this->model->getPerPage();
- if ($this->query->distinct) {
- $results = ($total = $this->toBase()->getCountForPagination([$columns[0]]))
- ? $this->forPage($page, $perPage)->get($columns)
- : $this->model->newCollection();
- } else {
- $results = ($total = $this->toBase()->getCountForPagination())
- ? $this->forPage($page, $perPage)->get($columns)
- : $this->model->newCollection();
- }
- return $this->paginator($results, $total, $perPage, $page, [
- 'path' => Paginator::resolveCurrentPath(),
- 'pageName' => $pageName,
- ]);
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement