laravel - 如何正确地将排序模型从我的控制器发送到 Laravel API 资源集合?
问题描述
这是我的控制器:
public function branchesNearby($lat, $lng)
{
$branches = Branch::all();
//Calculate distance between each branch and client
//Radius of earth is 6371 KM so multiply the result with radius of earth 6371*pi/180
foreach ($branches as $branch){
$branch['distance'] = sqrt(pow(($branch->lat - $lat), 2) + pow(($branch->lng - $lng), 2)) * 108;
}
//Sort by nearest first
$sortedBranches = $branches->sortBy('distance');
return BranchResource::collection($sortedBranches);
}
您可以看到我创建了一个额外的属性来计算用户位置和分支位置之间的距离。然后,我按距离对分支模型进行排序。但是,我得到的 api 响应是: API response
你可以看到它是一个对象。我不需要键“2”、“0”和“1”。我需要删除这个额外的包装,我需要它是一个像这样的对象数组: 正确的 API 但没有排序 当然,是排序导致它成为一个对象?我尝试了许多其他方法,其中之一是:
$sortedBranches = $collection->sortBy('distance');
$final = $sortedBranches->values()->toJson();
并将这个 $final 发送到资源集合。这给了我错误:“在文件 api 资源中的字符串上调用成员函数 first()”。这一定是小事,但我真的需要帮助。
更新:我之前没有发布我的资源,是这样的:
public function toArray($request)
{
return [
'id' => $this->id,
'shop' => $this->shop->name,
'shop_image' => asset('api/images/' . $this->shop->image_file),
'lat' => $this->lat,
'lng' => $this->lng,
'shop_logo' => asset('api/images/' . $this->shop->logo_file),
'distance' => $this->distance . " KM"
];
如果我使用我得到的错误:
$sortedBranches = $branches->sortBy('distance')->values()->all();
return BranchResource::collection($sortedBranches);
是: 错误
更新 3:
如果我不调用资源集合并像这样简单地输出 $sortedBranches:
return response()->json($sortedBranches, 200);
这里,api 响应的格式正确但数据不正确。这是它的外观: $sortedBranches
有没有办法我可以操纵 $sortedBranches 并像使用 BranchResource 一样显示输出?
解决方案
根据我们的故障排除,得到的解决方案应该是:
return BranchResource::collection($sortedBranches)->values()->all();
当您将集合传递给BranchResource
类的 collect 方法时,它会重新创建该集合。Laravel 看到您直接从控制器返回一个(集合)对象,并通过将其转换为 json 进行干预(我相信这是默认设置)。如果生成的 json 没有按照你想要的方式转换,你需要修改这个集合。因此我们需要修改BranchResource::collection()
集合,而不是$sortedBranches
集合。
编辑:
- 将 collect 方法修改为 collection;
推荐阅读
- swift - 只与某些物理实体交互而忽略其他实体
- docker - Pycharm中的Docker:远程文件X.py映射到本地路径Y.py,找不到
- mysql - 优化 MySQL 中连接键/值对表的查询
- node.js - post request with express error can't set headers after sent to clients 是否可以在 post req 中使用 fetch
- pandas - 如何在 REST API 调用之间实现缓存 pandas 数据帧值?
- c# - httpcontext.current.server.mappath 返回错误的路径
- python - pandas:groupby 1 列,求和,并删除重复的行
- google-app-maker - 如何使用 onBeforeSave 事件跟踪记录的关系值何时发生变化?
- unit-testing - Flutter:单元测试
- jenkins - Jenkins - 从节点查看实时 html 文件