pkr*_*cer 3 pagination json laravel
我想知道是否可以从简单查询中自定义返回对象在分页结果中的顺序.响应顺序现在是分页信息,后跟"data"对象,其中包含我搜索过的模型.我想知道是否有可能扭转顺序,所以它的产品信息后跟某种分页对象.
我的查询是:
return Product::paginate(100);
Run Code Online (Sandbox Code Playgroud)
我的结果是:
{"total":466,"per_page":100,"current_page":1,"last_page":5,"from":1,"to":100,"data":[{"id":28,"account_id":5,"created_by_id":14,"type":"accessory","title":"Product #28","description":"D","max_per_order":1,"stock":3565,"created_at":"1998-04-18 00:00:00","updated_at":"1994-10-28 00:00:00","deleted_at":null},{"id":44,"account_id":5,"created_by_id":36,"type":"registration","title":"Product #44","description":"Z","max_per_order":10,"stock":13739,"created_at":"2014-04-20 00:00:00","updated_at":"1991-06-03 00:00:00","deleted_at":null}]}
Run Code Online (Sandbox Code Playgroud)
我希望结果是这样的:
[products: [{"id":28,"account_id":5,"created_by_id":14,"type":"accessory","title":"Product #28","description":"D","max_per_order":1,"stock":3565,"created_at":"1998-04-18 00:00:00","updated_at":"1994-10-28 00:00:00","deleted_at":null},{"id":44,"account_id":5,"created_by_id":36,"type":"registration","title":"Product #44","description":"Z","max_per_order":10,"stock":13739,"created_at":"2014-04-20 00:00:00","updated_at":"1991-06-03 00:00:00","deleted_at":null},{"id":57,"account_id":5,"created_by_id":40,"type":"accessory","title":"Product #57","description":"Z","max_per_order":4,"stock":19376,"created_at":"1970-03-27 00:00:00","updated_at":"2001-01-01 00:00:00","deleted_at":null}], pagination: {"total":466,"per_page":100,"current_page":1,"last_page":5,"from":1,"to":100}]
Run Code Online (Sandbox Code Playgroud)
我该怎么做这样的事情?编写自己的分页代码会更容易吗?
oll*_*ead 11
没有办法使用laravel特定的措施来做到这一点,它需要你实际抓取数据并创建自己的自定义数组作为JSON返回.但是,这很简单,我在下面添加了一个例子.
$products = Product::paginate(100);
$response = [
'products' => $products->getItems()->toArray(),
'pagination' => [
'total' => $products->getTotal(),
'per_page' => $products->getPerPage(),
'current_page' => $products->getCurrentPage(),
'last_page' => $products->getLastPage(),
'from' => $products->getFrom(),
'to' => $products->getTo()
]
];
return Response::json($response);
Run Code Online (Sandbox Code Playgroud)
我最近用laravel创建了几个API,我遇到的一个问题是在保持统一响应的同时对数据进行分页,这就是我处理它的方式.
希望能帮助到你.
| 归档时间: |
|
| 查看次数: |
3691 次 |
| 最近记录: |