我有一个通过分页查询获得的集合:
$apps = $query->paginate(10);
结果是这样的:
我想在发送该集合之前对其进行排序,尤其是“数据”数组。我用“ sortBy”和“ sortByDesc”尝试了很多东西。没有成功。每次我使用这些方法时,分页都是“中断”的。
如何对通过分页获得的json进行排序?
Merci Dom
答案 0 :(得分:0)
您可以在分页结果之前使用orderBy
,orderByDesc
或orderByRaw
对查询进行排序:
$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;
}