我想知道是否可以自定义从简单查询的分页结果中返回对象的顺序。现在的响应顺序是分页信息,后面跟着包含我搜索的模型的"data"对象。我想知道是否有可能颠倒顺序,使其产品信息后面跟着某种分页对象。
我的查询是:
return Product::paginate(100);
结果是:
{"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}]}
我希望得到的结果是这样的:
[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}]
我该怎么做这样的事呢?编写自己的分页代码会更容易吗?
没有办法使用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);
我最近用laravel创建了几个api,我面临的一个问题是在保持统一响应的同时分页数据,这就是我如何处理它的。
希望能有所帮助。
Laravel已经包含了这个功能,试试这个
$products = Product::paginate(100)->toJson();
return $products