我想知道是否可以在简单查询的分页结果中自定义返回对象的顺序。响应顺序现在是分页信息,后跟“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}]
我将如何做这样的事情?编写自己的分页代码会更容易吗?
答案 0 :(得分: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);
我最近使用laravel创建了几个API,我遇到的一个问题是在保持统一响应的同时对数据进行分页,这就是我处理它的方式。
希望它有所帮助。
答案 1 :(得分:0)
Laravel已经包含此功能,试试这个
$products = Product::paginate(100)->toJson();
return $products