Laravel 4-如何在Eloquent的-> paginate()中使用'offset'代替'page'? [英] Laravel 4 - How to use 'offset' in stead of 'page' with Eloquent's ->paginate()?

查看:205
本文介绍了Laravel 4-如何在Eloquent的-> paginate()中使用'offset'代替'page'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将现有的REST API迁移到Laravel 4.1,并且该API当前使用 offset 作为querystring参数来指定记录的偏移量

I am migrating an existing REST API to Laravel 4.1, and the API currently uses offset as querystring parameter to specify what the offset of the records needs to be.

我想使用默认的Eloquent的paginate(),但是这些会搜索 page 查询字符串参数.当然,它使用页码(如2)而不是偏移量(如200).

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).

是否有一种简便的方法来配置paginate功能以适应这种情况?还是我需要使用->skip()->take()函数并自己链接到下一页?

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?

@Anam:我要使用:

@Anam: I want to use:

$warehouses = Warehouse::orderBy('name')
    ->paginate($perpage);

这可用于 http://example.org/api/warehouses?page=2,但是我希望它与 http://example.org/api/warehouses?offset一起使用= 200

This works with http://example.org/api/warehouses?page=2, but I want this to work with http://example.org/api/warehouses?offset=200

使用偏移量,我可以使用:

With the offset I can use:

$warehouses = Warehouse::orderBy('name')
    ->skip($offset)
    ->take($perpage)
    ->get();

但是我不能为API和Web视图使用相同的控制器.因此,我希望采用某种方法使第一个工作.

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视图使用相同的控制器.因此,我希望采用某种方法使第一个工作.

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.

为什么不呢?如果您已经知道?offset在API中可用,而?page在您的常规视图中可用.只需检测找到的并适当地应用它即可.

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.

也就是说,您可以检索查询构建器使用的分页器环境实例,并向其传递您定义的页码.

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.

这篇关于Laravel 4-如何在Eloquent的-> paginate()中使用'offset'代替'page'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆