在laravel中对分页变量排序

xienkqul  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(385)

我试图在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",
    },
]
nhn9ugyo

nhn9ugyo1#

总的来说

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

完整解决方案(假设函数仍返回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);

相关问题