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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…