简体   繁体   English

laravel - orderby 未显示正确结果

[英]laravel - orderby doesn't show correct results

I have a fairly simple query which I load and add an element to the object and then sort it based on that custom element.我有一个相当简单的查询,我加载并添加一个元素到 object,然后根据该自定义元素对其进行排序。 I'd like to take 20 records or paginate it but when I do so, alot of data vanishes.我想获取 20 条记录或对其进行分页,但是当我这样做时,很多数据都消失了。

This is my code.这是我的代码。 The piece below gets all the records.下面的一块得到了所有的记录。

$fighters = Fighter::all();

The below code gets the points which is in a function and adds it to the fighter, fighterPoints does not initially exist in the collection, it is created and populated below.下面的代码获取 function 中的点并将其添加到战斗机中,战斗机点最初不存在于集合中,它在下面创建和填充。

foreach ($fighters as $fighter) {
 $fighter->fighterPoints = $fighter->getFighterPoints($fighter->id);
}

Then i'd like to sort everything by those fighterPoints with the below function.然后我想用下面的 function 按这些 fighterPoints 对所有内容进行排序。

$sorted = $fighters ->sortByDesc(function ($item, $key) {
  return $item->fighterPoints ;
});

When i do this i get all the records which are around 9000, it then sorts on the fighterPoints correctly: The first record being something like [FighterName, 21309]当我这样做时,我得到所有大约 9000 条记录,然后它正确地对 fighterPoints 进行排序:第一条记录类似于 [FighterName, 21309]

When i do $fighters = Fighter::paginate(20);当我做$fighters = Fighter::paginate(20); it simply starts with [FighterName384, 200] which should be [FighterName, 21309] and just 20 results.它只是以 [FighterName384, 200] 开头,应该是 [FighterName, 21309] 并且只有 20 个结果。 The same thing happens with::take(20) method.同样的事情发生在::take(20) 方法上。

What am I doing wrong here?我在这里做错了什么? I am laravel 8.我是 laravel 8。

You want to paginate your $sorted variable right?!您想对 $sorted 变量进行分页吗? To do that you have to为此,您必须

use Illuminate\Pagination\Paginator; // add
use Illuminate\Support\Collection; // add
use Illuminate\Pagination\LengthAwarePaginator; //add

...(your code)

// add
public function paginate($items, $perPage = 5, $page = null, $options = [])
{
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
    $items = $items instanceof Collection ? $items : Collection::make($items);
    return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}

then, use that $sorted this way:然后,以这种方式使用 $sorted:

$fighters = $this->paginate($sorted);

reference: https://www.itsolutionstuff.com/post/laravel-6-paginate-with-collection-or-arrayexample.html参考: https://www.itsolutionstuff.com/post/laravel-6-paginate-with-collection-or-arrayexample.html

—————- EDIT ———— - - - 编辑 - -

Sorry I misunderstood your question, If you want to order eloquent, here is how you do it对不起,我误解了你的问题,如果你想订购 eloquent,这里是你的做法

$fighters = Fighter::orderBy('fighterPoints', 'desc')->paginate(20);

I hope that's what you are looking for!我希望这就是你要找的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM