每次使用的时候都需要,这样:
use League\Fractal;
use League\Fractal\Manager;
use League\Fractal\Resource\Collection;
use League\Fractal\Serializer\DataArraySerializer;
use League\Fractal\Serializer\ArraySerializer;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Serializer\JsonApiSerializer;
还有这样:
return (new Manager())->setSerializer(new ArraySerializer())
->parseIncludes('user')
->createData(
(new Collection($dueDetails->paginate(10)->getCollection(), new ProjectTransformer(), 'data'))
->setPaginator(new IlluminatePaginatorAdapter($dueDetails->paginate(10)))
->setMeta([
'count_due_capital' => $dueDetails->count(),
'sum_due_capital' => $dueDetails->sum('due_capital')
])
)
->toArray();
感觉很痛苦。
然后代码就变成这样:
return fractal()
->withResourceName('data')
->collection($dueDetails->paginate(10)->getCollection())
->transformWith(new ProjectTransformer())
->paginateWith(new IlluminatePaginatorAdapter($dueDetails->paginate(10)))
->addMeta([
'count_due_capital' => $dueDetails->count(),
'sum_due_capital' => $dueDetails->sum('due_capital')
])
->includeUser()
->toArray();