我想使用laravel-datatables-fractal来使用 Fractal 转换服务器端响应。
Product
首先,我为这样的模型编写了一个变压器:
class ProductTransformer extends TransformerAbstract
{
protected $availableIncludes = [
'prices'
];
public function transform(Product $product)
{
$transforms = [
'product_id' => $product->product_id,
'code' => $product->code,
'title' => $product->title,
'description' => $product->description,
];
return $transforms;
}
public function includePrices(Product $product)
{
$prices = $product->prices;
return $this->collection($prices, new PriceTransformer, FALSE);
}
}
如您所见,有一个包含的prices
属性使用另一个名为PriceTransformer
.
在生成ProductController
并返回所有产品的结果作为数据表格式的响应中,我有一个datatable
这样的方法:
public function datatable(Request $request)
{
return app('datatables')->of(Product::all())
->setTransformer(new ProductTransformer)
// ->setSerializer(new CustomArraySerializer())
->make(TRUE);
}
返回响应,但我遇到的一个问题是:当我想返回prices
包含的属性时,它以如下data
属性返回:
{
"draw": 0,
"recordsTotal": 8,
"recordsFiltered": 8,
"data": [
{
"product_id": 1,
"title": "Product Title 1",
"for_sale": true,
"for_purchase": true,
"changeable": false,
"returnable": false,
"sale_price": "40000.00",
"purchase_price": "5000.00",
"creator": 1,
"created_at": "2017-12-11 12:21:49",
"updated_at": "2017-12-14 11:55:52",
"prices": {
"data": [
{
"sale_price": "30000.00",
"created_at": "2017-12-11 12:21:49"
},
{
"sale_price": "40000.00",
"created_at": "2017-12-11 12:39:00"
},
]
}
},
{
"product_id": 11,
"title": "Product Title 11",
"for_sale": true,
"for_purchase": true,
"changeable": false,
"returnable": false,
"sale_price": "50000.00",
"purchase_price": "40000.00",
"creator": 1,
"created_at": "2017-12-16 11:07:43",
"updated_at": "2017-12-16 11:07:43",
"prices": {
"data": [
{
"sale_price": "50000.00",
"created_at": "2017-12-16 11:07:43"
}
]
}
}
],
"input": {
"include": "prices"
}
}
我想data
从包含的属性中删除,它们采用这种格式,例如:
"prices": [
{
"sale_price": "50000.00",
"created_at": "2017-12-16 11:07:43"
}
]
即使我添加了一个序列化程序(如您在上面的代码中看到的并已注释),其内容如下,我将其用于所有其他响应并且运行良好:
class CustomArraySerializer extends ArraySerializer
{
public function collection($resourceKey, array $data)
{
if ($resourceKey === FALSE) {
return $data;
}
return ['success' => TRUE, 'result' => $data];
}
public function item($resourceKey, array $data)
{
if ($resourceKey === FALSE) {
return $data;
}
return ['success' => TRUE, 'result' => $data];
}
}
但是当使用它时,我得到了这个错误:
{
"draw": 0,
"recordsTotal": 8,
"recordsFiltered": 0,
"data": [],
"error": "Exception Message:\n\nUndefined index: data"
}
什么是问题,如何解决?