如何根据分页结果对集合进行排序

时间:2018-11-13 11:03:09

标签: laravel

我有一个通过分页查询获得的集合:

$apps = $query->paginate(10);

结果是这样的:

enter image description here

我想在发送该集合之前对其进行排序,尤其是“数据”数组。我用“ sortBy”和“ sortByDesc”尝试了很多东西。没有成功。每次我使用这些方法时,分页都是“中断”的。

如何对通过分页获得的json进行排序?

Merci Dom

2 个答案:

答案 0 :(得分:0)

您可以在分页结果之前使用orderByorderByDescorderByRaw对查询进行排序:

docs:

$apps = $query->orderBy('created_at')->paginate(10);

答案 1 :(得分:0)

use Illuminate\Pagination\LengthAwarePaginator;


$sortedApps = $query->get()->sortBy('name');

$result = $this->paginateCollection($sortedApps,50);


public function paginateCollection(
    $collection, 
    $perPage, 
    $pageName = 'page', 
    $fragment = null
) : LengthAwarePaginator
    {
        $currentPage = LengthAwarePaginator::resolveCurrentPage($pageName);
        $currentPageItems = $collection->slice(($currentPage - 1) * $perPage, $perPage);
        parse_str(request()->getQueryString(), $query);
        unset($query[$pageName]);
        $paginator = new LengthAwarePaginator(
            $currentPageItems,
            $collection->count(),
            $perPage,
            $currentPage,
            [
                'pageName' => $pageName,
                'path' => LengthAwarePaginator::resolveCurrentPath(),
                'query' => $query,
                'fragment' => $fragment
            ]
        );

        return $paginator;
    }