简体   繁体   中英

Laravel 5: Need to sort a grouped collection by an attribute of first item of each group

I have a collection of some Eloquent model items from my database which are grouped by an attribute using groupBy() , I need to sort that collection by another attribute of the first item of each group but preserve the initial structure. How can I achieve this, if possible at all?

groupBy returns a collection, so you should still be able to use the sortBy method. You need to use a callback to get the attribute value from the first item in each group rather than just giving it a string.

$sorted = $groups->sortBy(function ($group, $key) {
    return $group->first()->someAttribute;
});

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