Reputation: 13
I have a set of objects Person
that I would like to sort based on a score that is calculated by a function on the object Score()
.
While I can easily display the Score()
in ModelAdmin I am unable to sort by that field as it's not a db field. The score changes each day based on a few of the other fields in the db so it's not something that would be suitable to store itself.
I suspected there would be a function which is the equivilent of filterByCallback()
such as sortByCallback()
but I can't seem to find that existing.
I don't need it to be added in the ModelAdmin gridField but I would like to use it in a report. How have others got around this problem?
Cheers
Upvotes: 1
Views: 1008
Reputation: 5875
You could always sort with the native PHP methods. Eg.
$list = Person::get()->toArray();
usort($list, function($a, $b){
// will sort in descending order. To reverse, swap $b and $a
return $b->Score() - $a->Score();
});
If you need to, you can then still convert to an ArrayList
:
ArrayList::create($list);
As UncleCheese pointed out in his comment, this can be quite slow and memory intensive… it really depends on how many records you're planning to sort.
Upvotes: 3