我需要将多个对象发送到 api 资源。所以我在数组中返回多个对象。一切正常但没有显示任何分页元数据。像 Current_page,next_page url 等
return [
'across_city' => ServiceProviderCollection::collection($across_city),
'near_by' => ServiceProviderCollection::collection($near_by)
];
我的资源
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class ServiceProviderCollection extends Resource
{
public function toArray($request)
{
return
[
'name'=>$this->forename,
'rating'=>$this->rating,
'price'=>$this->price,
'distance'=>round($this->distances,1),
];
}
}
我的 Controller : 在这里我有两种类型的用户。 near_by 用户和整个城市的用户。我将它们作为数组发送到 ServiceProviderCollection。
$user_city = $userObj->location->city;
$locationObj = Location::whereNotIn('id', $blockeduser)->where('city',$user_city)->first();
$across_city = $locationObj->users()->simplePaginate(20);
$near_by = User::join('locations as l', 'users.location_id', '=', 'l.id')
->select('users.*', DB::raw('(6371 * acos(cos(radians(' . $coordinates['latitude'] . ')) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(' . $coordinates['longitude'] . ')) + sin(radians(' . $coordinates['latitude'] . ')) * sin(radians(`lat`)))) as distances'))
->having('distances', '<', $max_distance)
->orderBy('distances', 'ASC')
->where('role_id',2)
->whereNotIn('id', $blockeduser)
->simplePaginate(20);
return [
'across_city' => ServiceProviderCollection::collection($across_city),
'near_by' => ServiceProviderCollection::collection($near_by)
];
我想要带分页的 Json 数据。
{"data":{
"across_city": [
{
"name": "??",
"rating": 0,
"price": 0,
"distance": 0,
}
],
"links": {
"first": "",
"last": "",
"prev": null,
"next": ""
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 3,
"path": "",
"per_page": 2,
"to": 2,
"total": 6
},
{
"near_by": [
{
"name": "??",
"rating": 0,
"price": 0,
"distance": 0,
}
],
"links": {
"first": "",
"last": "",
"prev": null,
"next": ""
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 3,
"path": "",
"per_page": 2,
"to": 2,
"total": 6
}
}
最佳答案
我不知道 ServiceProviderCollection
的目的是什么。如果它创建一个常规集合,则有一个 better way to do so .
为了能够对简单的集合进行分页,您需要将此辅助函数添加到您的基础中:
function paginateCollection($items, $perPage = 15, $page = null, $options = [])
{
$page = $page ?: (\Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof \Illuminate\Support\Collection ? $items : \Illuminate\Support\Collection::make($items);
return new \Illuminate\Pagination\LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
有了这个功能你就可以制作
return [
'across_city' => paginateCollection(collect($across_city), 20),
'near_by' => paginateCollection(collect($near_by), 20)
];
编辑
你有生成相应的资源合集吗?
像这样:php artisan make:resource Cities --collection
如果是这样,您可以返回 paginated resource collection
关于laravel - 返回数组 Api 资源对象时分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52258721/