在尝试在集合中使用Resource之后,我试图获取一个分页的CollectionResource,但是分页数据始终丢失。
BillController:
$bill = Bill::with('category');
return new BillCollectionResource( BillResource::collection($bill->paginate(10)) );
BillResource
public function toArray($request)
{
$data = parent::toArray($request);
$data['lorem'] = 'ipsum';
$data['foo'] = 'bar';
return $data;
}
BillCollectionResource
public function toArray($request)
{
return [
'data' => $this->collection,
'rows_count' => $rows_count,
'total_balance' => $total_balance,
'total_num_debits' => $total_num_debits,
'total_num_credits' => $total_num_credits,
'total_balance_debits' => $total_balance_debits,
'total_balance_credits' => $total_balance_credits,
];
}
预期结果:
{
data: [...],
rows_count : 16,
total_balance : 200.00,
total_num_debits : 8,
total_num_credits : 4,
total_balance_debits : -100.00,
total_balance_credits : 100.00,
links:
{
first: 'http://localhost:8001/api/...',
last: 'http://localhost:8001/api/...',
next: 'http://localhost:8001/api/..',
prev: null,
},
meta:
{
to: 5,
from: 1,
path: 'http://localhost:8001/api/...',
total: 75
per_page: 5,
last_page: 15,
current_page: 1,
}
}
当前结果:
{
data: [...],
rows_count : 16,
total_balance : 200.00,
total_num_debits : 8,
total_num_credits : 4,
total_balance_debits : -100.00,
total_balance_credits : 100.00,
}
我也尝试手动添加分页,但是下面的所有$request
方法都未定义。
BillCollectionResource
'pagination' =>
[
'total' => $request->total(),
'count' => $request->count(),
'per_page' => $request->perPage(),
'current_page' => $request->currentPage(),
'total_pages' => $request->lastPage()
]
这种行为背后的原因是什么?预先感谢。