我使用这个库将分形变换器添加到我的json输出中。
//This is main tranformer for service provider enquiry transformer
class CustomerVehicleTransformer extends TransformerAbstract {
protected $defaultIncludes = [
'service_provider_enquries'
];
public function transform(CustomerVehicle $customerVehicle) {
return [
'id' => (int) $customerVehicle->id,
'status' =>$customerVehicle->vehiclenumber
];
}
public function includeServiceProviderEnquries(CustomerVehicle $customerVehicle) {
$serviceProvider = $customerVehicle->service_provider_enquries;
return $this->item($serviceProvider, new ServiceProvidersEnquiryTransformer);
}
}

class ServiceProvidersEnquiryTransformer extends TransformerAbstract {
public function transform(ServiceProvidersEnquiry $book) {
return [
'modeofpayment' => (int) $book->modeofpayment
];
}
}

调用
$manager =new Fractal\Manager();
if (isset($_GET['include'])) {
$manager->parseIncludes($_GET['include']);
}
$json = $manager->createData($resource)->toJson();
echo $json;

当我尝试运行此代码时,会抛出以下错误:
参数1传递给 应用程序\ Acme的\ FractalTransformers \ ServiceProvidersEnquiryTransformer ::变换() 必须是App \ ServiceProvidersEnquiry的实例,null给定,调用 在/home/aidor/Documents/ozoServer/vendor/league/fractal/src/Scope.php中 在307行并定义
可能是什么问题?请提供一些defaultincludes和availableIncludes的例子。
答案 0 :(得分:2)
错误是$resource
为空,您需要将ServiceProvidersEnquiry
的实例传递给它,您还缺少一些关键代码行来设置响应。仔细检查文档,检查您是否正确行事,并了解为什么它不起作用:http://fractal.thephpleague.com/transformers/
你应该做这样的事情我想:
// set up data
$enquiry = App\ServiceProvidersEnquiry::first();
// set up fractal manager
$manager = new Fractal\Manager();
if (isset($_GET['include'])) {
$manager->parseIncludes($_GET['include']);
}
$fractal->setSerializer(new Fractal\Serializer\ArraySerializer());
// set up response item
$response = new Fractal\Resource\Item($enquiry, new \PathToYourTransformer\ServiceProvidersEnquiryTransformer);
return response()->json($fractal->createData($response)->toArray());