laravel 在分页功能中使用限制参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43473707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:48:45  来源:igfitidea点击:

Using limit parameter in paginate function

laraveleloquentlaravel-query-builderlaravel-pagination

提问by Damjan Krstevski

Is it possible to use 'limit' parameter in paginate() function?

是否可以在 paginate() 函数中使用“limit”参数?

I'm trying this:

我正在尝试这个:

$users->where(...)->limit(50)->paginate($page)

...and now, if I have 100 users in the database then the response from paginate function will be all 100 users instead of 50 (or number of users defined with limit parameter).

...现在,如果我在数据库中有 100 个用户,那么 paginate 函数的响应将是所有 100 个用户,而不是 50 个(或使用 limit 参数定义的用户数)。

So, my question is: is it possible to implement limit parameter when I use paginate function?

所以,我的问题是:当我使用分页功能时是否可以实现限制参数?

回答by patricus

No, it's not possible to limit the query when using pagination.

不,使用分页时不可能限制查询。

Query pagination uses skip()and limit()internally to select the proper records. Any limit()applied to the query will be overwritten by the pagination requirements.

查询分页使用skip()和 在limit()内部选择正确的记录。任何limit()应用于查询的内容都将被分页要求覆盖。

If you'd like to paginate a subset of results, you will need to get the results first, and then manually create a paginator for those results.

如果您想对结果的子集进行分页,则需要先获取结果,然后为这些结果手动创建分页器。

回答by mustardandrew

Use LengthAwarePaginator.

使用 LengthAwarePaginator。

Example:

例子:

$total = 50;
$perPage = 10;
$users = $users->where(...)->paginate($page);

$users = new LengthAwarePaginator(
    $users->toArray()['data'], 
    $users->total() < $total ? $users->total() : $total, 
    $perPage, 
    $page
);

回答by Raghu Aryan

If you want use limit in Laravel query then will we use offset for pagination.

如果您想在 Laravel 查询中使用限制,那么我们将使用偏移量进行分页。

First time

第一次

$users->where(...)->limit(10)->offset(0);

$users->where(...)->limit(10)->offset(0);

On next click

下次点击

$users->where(...)->limit(10)->offset(10);

$users->where(...)->limit(10)->offset(10);

More next click

更多下次点击

$users->where(...)->limit(10)->offset(20);

$users->where(...)->limit(10)->offset(20);

回答by Marcelo Agimóvel

By default, the current page is detected by the value of the page query string argument on the HTTP request. Of course, this value is automatically detected by Laravel, and is also automatically inserted into links generated by the paginator.

默认情况下,当前页面由 HTTP 请求上的页面查询字符串参数的值检测。当然,这个值是由 Laravel 自动检测的,也会自动插入到分页器生成的链接中。

So, inform page and pagination and all should be fine.

所以,通知页面和分页,一切都应该没问题。