【发布时间】:2017-12-10 00:57:30
【问题描述】:
我一直在使用 laravel 来构建我的 API。我使用转换器来转换模型对象中的数据。
现在我有一个来自 API 的响应而不是数据库作为数据源,我想将该数据转换回用户,但我无法这样做。
我的控制器
public function rocByName(Request $request)
{
try {
$this->roc_by_name_validator->with( $request->all() )->passesOrFail();
$company_name = $request->input('company_name');
$result = $this->my_service->getDetailsByName($company_name); //$result has the response object from the API which I want to transform and give it as a response.
return $this->response->collection($result,new OnboardingTransformer()); //Tried using tranformer like this
}
catch (ValidatorException $e) {
dd($e);
}
}
我的变压器
<?php
namespace Modules\Onboarding\Transformers;
use League\Fractal\TransformerAbstract;
use App\Entities\OnboardingEntity; //I dont have an entity since the response is coming from an API!! What will give here?
/**
* Class OnboardingTransformerTransformer
* @package namespace App\Transformers;
*/
class OnboardingTransformer extends TransformerAbstract
{
/**
* Transform the \OnboardingTransformer entity
* @param \OnboardingTransformer $model
*
* @return array
*/
public function transform(OnboardingEntity $data_source)
{
return [
'company_name' => $data_source->company_name,
];
}
}
这里的 OnboardingEntity 是指理想情况下来自数据库的数据。在这里,我不是从数据库中获取数据,而是我的数据来自 API 源。我该怎么做。我在这里有点困惑。有人可以给出解决方案吗?
$result 有以下响应
[
[
{
"companyID": "U72400MHTC293037",
"companyName": "pay pvt LIMITED"
},
{
"companyID": "U74900HR2016PT853",
"companyName": "dddd PRIVATE LIMITED"
}
]
]
【问题讨论】:
-
我相信您不需要将其转换为收藏。您可以直接将数组传递给转换器。
-
@AdnanMumtaz 那也很好。您可以在答案中添加示例代码吗?
-
$result = $this->my_service->getDetailsByName($company_name)你是在接收$results中的集合还是数组 -
@AdnanMumtaz 我已经用 $result 中的示例响应更新了这个问题。请检查。它是一个数组
-
@companyName 公司名称怎么可以是整数?
标签: php laravel transformer dingo-api thephpleague-fractal