【发布时间】:2019-02-14 22:38:05
【问题描述】:
我需要将多个对象发送到 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),
];
}
}
我的控制器: 这里我有两种类型的用户。 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的用途是什么,$across_city/$near_by中的内容是什么? -
好的,谢谢你的详细信息,现在更清楚了。您是否通过以下方式获得分页数据:
return new ServiceProviderCollection(User::paginate());?
标签: laravel api pagination eloquent