🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Collection类 ### 介绍 `October\Rain\Support\Collection`类提供一个流畅,方便的包装用于与数据的数组工作。例如,查看以下代码。我们将从数组创建一个新的集合实例,`strtoupper`在每个元素上运行该函数,然后删除所有空元素: ~~~ $collection = new October\Rain\Support\Collection(['stewie', 'brian', null]); $collection = $collection ->map(function ($name) { return strtoupper($name); }) ->reject(function ($name) { return empty($name); }) ; ~~~ 在`Collection`类允许您链中的方法来执行流利映射和底层数组的减少。通常,每个`Collection`方法都返回一个全新的`Collection`实例。 ### [](https://octobercms.com/docs/services/collections#creating-collections)创建收藏 如上所述,将数组传递给`October\Rain\Support\Collection`类的构造函数将为给定数组返回一个新实例。因此,创建集合非常简单: ~~~ $collection = new October\Rain\Support\Collection([1, 2, 3]); ~~~ 默认情况下,[数据库模型的](https://octobercms.com/docs/database/model)集合始终作为`Collection`实例返回;但是,请`Collection`在适合您的应用程序的任何地方随意使用该类。 ### 高阶消息 集合还支持“高级消息”,这是对集合执行常见操作的捷径。提供更高阶的信息收集方法有:[`average`](https://octobercms.com/docs/services/collections#method-average),[`avg`](https://octobercms.com/docs/services/collections#method-avg),[`contains`](https://octobercms.com/docs/services/collections#method-contains),[`each`](https://octobercms.com/docs/services/collections#method-each),[`every`](https://octobercms.com/docs/services/collections#method-every),[`filter`](https://octobercms.com/docs/services/collections#method-filter),[`first`](https://octobercms.com/docs/services/collections#method-first),[`flatMap`](https://octobercms.com/docs/services/collections#method-flatmap),[`groupBy`](https://octobercms.com/docs/services/collections#method-groupby),[`keyBy`](https://octobercms.com/docs/services/collections#method-keyby),[`map`](https://octobercms.com/docs/services/collections#method-map),[`max`](https://octobercms.com/docs/services/collections#method-max),[`min`](https://octobercms.com/docs/services/collections#method-min),[`partition`](https://octobercms.com/docs/services/collections#method-partition),[`reject`](https://octobercms.com/docs/services/collections#method-reject),[`some`](https://octobercms.com/docs/services/collections#method-some),[`sortBy`](https://octobercms.com/docs/services/collections#method-sortby),[`sortByDesc`](https://octobercms.com/docs/services/collections#method-sortbydesc),[`sum`](https://octobercms.com/docs/services/collections#method-sum),和[`unique`](https://octobercms.com/docs/services/collections#method-unique)。 每个高阶消息都可以作为集合实例上的动态属性来访问。例如,让我们使用`each`高阶消息在集合内的每个对象上调用一个方法: ~~~ $users = User::where('votes', '>', 500)->get(); $users->each->markAsVip(); ~~~ 同样,我们可以使用`sum`较高顺序的消息来收集用户集合的“票数”总数: ~~~ $users = User::where('group', 'Development')->get(); return $users->sum->votes; ~~~