laravel 如何在分页集合中使用转换

How to use transform in paginated collection in laravel

我想在 laravel 5.5 的分页集合中使用 map 或 transform,但我正在努力工作

这是我试图做的,但是 getCollectionLengthAwarePaginator 中不可用,就像我们在以前的 laravel 版本中所做的那样,请参阅:How to transform paginated collection

 $query = User::filter($request->all()
        ->with('applications');

    $users = $query->paginate(config('app.defaults.pageSize'))
        ->transform(function ($user, $key) {
            $user['picture'] = $user->avatar;

            return $user;
        });

这是我收到的结果,但我的结果中没有分页详细信息

如何return 转换包含分页详细信息的集合?

您应该在检索集合和转换之前进行分页,如下所示:

$query = User::filter($request->all())->with('applications')->paginate(50);

$users = $query->getCollection()->transform(function ($user, $key) {
    //your code here
});

dd($users);

它应该会给你想要的结果。

我最终在 AppServiceProvider

中构建了自定义分页功能

use Illuminate\Support\Collection;

registerAppServiceProvider

 Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
        $page = $page ?: \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage($pageName);
        return new \Illuminate\Pagination\LengthAwarePaginator(
            $this->forPage($page, $perPage),
            $total ?: $this->count(),
            $perPage,
            $page,
            [
                'path' => \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPath(),
                'pageName' => $pageName,
            ]
        );
    });

对于 Laraval >= 8.x:如果你想对分页查询生成器结果的集合执行 transform() 而不是对完整集合进行分页,可以使用方法through():

User::filter($request->all()
   ->with('applications')
   ->paginate(config('app.defaults.pageSize'))
   // through() will call transform() on the $items in the pagination object
   ->through(function ($user, $key) {
      $user['picture'] = $user->avatar;

      return $user;
   });

您的问题是您正在打印保存当前页面中用户数组的 $users 变量。要获取分页列表,请尝试 return/print $query

所以你的代码应该如下:

    $query = User::filter($request->all()
            ->with('applications');
    
        $users = $query->paginate(config('app.defaults.pageSize'))
            ->transform(function ($user, $key) {
                $user['picture'] = $user->avatar;
    
                return $user;
            });
return response()->json($query);

编码愉快!