Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

php - 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.

question from:https://stackoverflow.com/questions/65837515/laravel-orderby-doesnt-show-correct-results

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want to paginate your $sorted variable right?! To do that you have to

use IlluminatePaginationPaginator; // add
use IlluminateSupportCollection; // add
use IlluminatePaginationLengthAwarePaginator; //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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...