简体   繁体   English

如何限制 laravel 分页中的页面数量?

[英]How to limit amount of pages in laravel pagination?

I have a pagination and try to limit the amount of pages for that pagination.我有一个分页并尝试限制该分页的页数。 Every page has 50 results and the maximum amount of pages I want for this pagination is 200 (10k total entries from the table).每页有 50 个结果,我希望这个分页的最大页数是 200(表中的总条目数为 10k)。 I tried the following:我尝试了以下方法:

$page_count = 50;
$users = DB::Table('user_totalpoints')->where('points', '>', 0)
        ->orderBy('points', 'desc')
        ->orderBy('id', 'asc')
        ->take(10000)
        ->paginate($page_count);

The result of this is a pagination with 50 results per page but with ALL entries from the user_totalpoints table.这样做的结果是一个分页,每页有 50 个结果,但所有条目都来自 user_totalpoints 表。 take(10000) is ignored as there are only 50 taken by the pagination. take(10000) 被忽略,因为分页只有 50 个。 So instead of maximum 200pages I now have thousands.因此,我现在有数千页,而不是最多 200 页。

How can I limit the amount of pages for my pagination in laravel?如何限制 laravel 中分页的页数?

$collection = UserTotalPoint::where('points', '>', 0)
                      ->orderby('points', 'desc')
                      ->orderby('id', 'desc')
                      ->take(10000)
                      ->get();


$perPage = 50;

$currentPage = LengthAwarePaginator::resolveCurrentPage();

if ($currentPage == 1) {
    $start = 0;
}
else {
    $start = ($currentPage - 1) * $perPage;
}

$currentPageCollection = $collection->slice($start, $perPage)->all();

$paginatedTop = new LengthAwarePaginator($currentPageCollection, count($collection), $perPage);

$paginatedTop->setPath(LengthAwarePaginator::resolveCurrentPath());


return view('topPoints', ['top' => $paginatedTop ]);

Manual Paginator LengthAwarePaginator手动分页器 LengthAwarePaginator

// limit page max to 200 and min to 1
$this->validate($request, [
    'page' => 'required|integer|min:1|max:200'
]);
$page = $request->get('page');
$page_count = 50;
$total = 10000;

$users = DB::Table('user_totalpoints')->where('points', '>', 0)
    ->orderBy('points', 'desc')
    ->orderBy('id', 'asc')
    ->forPage($page, $page_count)
    ->get();
/**
 * use Illuminate\Pagination\LengthAwarePaginator;
 */
$paginator = new LengthAwarePaginator($users, $total, $page_count, $page);
dd($paginator->toArray()); // view result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM