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

时间:2018-11-26 04:06:21

标签: 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);

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

{
"0":{
      "id": "1",
      "name": "somename",
      "total": "15",
    },
"1":{
      "id": "2",
      "name": "somename2",
      "total": "100",
    },
"2":{
      "id": "3",
      "name": "somename5",
      "total": "26",
    },
}

我要达到的目标是:

"current_page": 1,
"data": [
  {
      "id": "2",
      "name": "somename2",
      "total": "100",
    },
 {
      "id": "3",
      "name": "somename5",
      "total": "26",
    },
 {
      "id": "1",
      "name": "somename",
      "total": "15",
    },
]

1 个答案:

答案 0 :(得分:1)

一般

$ 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()
);

完整解决方案(假设aFunction仍返回Paginator对象)

//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);