简体   繁体   中英

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. I'd like to take 20 records or paginate it but when I do so, alot of data vanishes.

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.

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

Then i'd like to sort everything by those fighterPoints with the below function.

$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]

When i do $fighters = Fighter::paginate(20); it simply starts with [FighterName384, 200] which should be [FighterName, 21309] and just 20 results. The same thing happens with::take(20) method.

What am I doing wrong here? I am laravel 8.

You want to paginate your $sorted variable right?! 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:

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

reference: 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

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

I hope that's what you are looking for!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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