我使用这个库将分形转换器添加到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传递给
app\acme\fractaltransformers\serviceprovidersenquirytransformer::transform()
必须是app\serviceprovidersenquiry的实例,给定空值,调用
在/home/aidor/documents/ozoserver/vendor/league/fractal/src/scope.php中
在线307和定义
有什么问题吗?请给出一些defaultincludes和availableincludes的示例。

最佳答案

错误是说$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());

10-06 02:23