在 Laravel 中对分页变量进行排序

Ine*_*ons 2 mysql laravel laravel-5 laravel-query-builder

我正在尝试在 Laravel 中对分页查询结果进行排序。我需要通过将所有内容的末尾降到我的分页变量来进行排序。

例子:

//get some data attach to variable
$variable = DB::table('exampletable')
->where('id',$somevariable)
->select('id','name')
->paginate(10);

//this function will send the variable and attach **total** on each object
$variable = $this->aFunction($variable);

//What I am trying to do, THIS is where I have to sort in the data flow
$variable->sortBy('total', 'desc');

//return data in json format
return response()->json($variable);
Run Code Online (Sandbox Code Playgroud)

我试过像上面说的那样对它进行排序,但我最终得到的变量只是在每个段/对象上都有名称。我已经尝试过,这是我不断得到的结果:

{
"0":{
      "id": "1",
      "name": "somename",
      "total": "15",
    },
"1":{
      "id": "2",
      "name": "somename2",
      "total": "100",
    },
"2":{
      "id": "3",
      "name": "somename5",
      "total": "26",
    },
}
Run Code Online (Sandbox Code Playgroud)

我想要达到的是这个结果:

"current_page": 1,
"data": [
  {
      "id": "2",
      "name": "somename2",
      "total": "100",
    },
 {
      "id": "3",
      "name": "somename5",
      "total": "26",
    },
 {
      "id": "1",
      "name": "somename",
      "total": "15",
    },
]
Run Code Online (Sandbox Code Playgroud)

And*_*ers 5

一般来说

$paginatedUsers 是 LengthAwarePaginator 的一个实例,这里记录:https ://laravel.com/api/5.7/Illuminate/Pagination/LengthAwarePaginator.html#method_presenter

我们可以setCollection用来改变底层集合。并items()仅提取当前页面上的对象。然后在收集它之后,我们可以随意排序。

$paginatedUsers = User::paginate(3)

$paginatedUsers->setCollection(
    collect(
        collect($paginatedUsers->items())->sortBy('name')
    )->values()
);
Run Code Online (Sandbox Code Playgroud)

完整解决方案(假设 aFunction 仍然返回一个分页器对象)

//get some data attach to variable
$variable = DB::table('exampletable')
->where('id',$somevariable)
->select('id','name')
->paginate(10);

//this function will send the variable and attach **total** on each object
$variable = $this->aFunction($variable);

$variable->setCollection(
    collect(
        collect($variable->items())->sortByDesc('total')
    )->values()
);

//return data in json format
return response()->json($variable);
Run Code Online (Sandbox Code Playgroud)