简体   繁体   English

Laravel 5:需要按每组第一项的属性对分组的集合进行排序

[英]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. 我从数据库中收集了一些雄辩的模型项,并使用groupBy()将其按属性分组,我需要按每个组的第一项的另一个属性对该集合进行排序,但要保留初始结构。 How can I achieve this, if possible at all? 如果可能的话,我该如何实现?

groupBy returns a collection, so you should still be able to use the sortBy method. groupBy返回一个集合,因此您仍然应该能够使用sortBy方法。 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;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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