Laravel 4 - 如何在 Eloquent 的 ->paginate() 中使用“偏移量”而不是“页面”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20759969/
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
Laravel 4 - How to use 'offset' in stead of 'page' with Eloquent's ->paginate()?
提问by Casper Bakker
I am migrating an existing REST API to Laravel 4.1, and the API currently uses offset
as querystring parameter to specify what the offsetof the records needs to be.
我正在将现有的 REST API 迁移到 Laravel 4.1,该 API 目前offset
用作查询字符串参数来指定记录的偏移量需要是什么。
I would like to use the default Eloquent's paginate()
, but these searches for the page
querystring parameter. And of course it uses the page number (like 2) instead of the offset (like 200).
我想使用默认的 Eloquent paginate()
,但这些搜索page
查询字符串参数。当然,它使用页码(如 2)而不是偏移量(如 200)。
Is there an easy way to configure the paginate
function to this situation? Or do I need to use ->skip()
and ->take()
functions and make the links to the next page myself?
有没有一种简单的方法可以将paginate
功能配置为这种情况?或者我是否需要自己使用->skip()
和->take()
运行并链接到下一页?
@Anam: I want to use:
@Anam:我想使用:
$warehouses = Warehouse::orderBy('name')
->paginate($perpage);
This works with http://example.org/api/warehouses?page=2, but I want this to work with http://example.org/api/warehouses?offset=200
这适用于http://example.org/api/warehouses?page=2,但我希望它与http://example.org/api/warehouses?offset=200 一起使用
With the offset I can use:
使用偏移量我可以使用:
$warehouses = Warehouse::orderBy('name')
->skip($offset)
->take($perpage)
->get();
But then I cannot use the same controller for the API and the web view. So I would prefer some way to make the first one working.
但是我不能为 API 和 Web 视图使用相同的控制器。所以我更喜欢某种方式让第一个工作。
采纳答案by Aken Roberts
But then I cannot use the same controller for the API and the web view. So I would prefer some way to make the first one working.
但是我不能为 API 和 Web 视图使用相同的控制器。所以我更喜欢某种方式让第一个工作。
Why not? If you already know ?offset
will be available in the API, and ?page
in your normal view. Just detect which is found and apply it appropriately.
为什么不?如果您已经知道?offset
将在 API 中可用,并且?page
在您的正常视图中。只需检测找到哪个并适当应用即可。
That said, you can retrieve the paginator environment instance the query builder uses and pass it a page number that you define.
也就是说,您可以检索查询构建器使用的分页器环境实例,并将您定义的页码传递给它。
$perPage = 50;
$currentPage = 1;
if ($offset = Input::get('offset'))
{
$currentPage = ($offset / $perPage);
}
Warehouse::resolveConnection()->getPaginator()->setCurrentPage($currentPage);
$warehouses = Warehouse::orderBy('name')->paginate($perpage);
Note that, while I tested this and it works, I don't know how much it will affect other queries that you might run on the same page. Look into it, use with caution.
请注意,虽然我对此进行了测试并且它有效,但我不知道它会对您可能在同一页面上运行的其他查询产生多大影响。仔细看看,谨慎使用。