Eloquent:集合

简介

Eloquent 返回的所有多结果集都是 Illuminate\Database\Eloquent\Collection 对象的实例,包括通过 get 方法或通过关联获取的结果。Eloquent 集合对象继承自 Laravel 的 集合基类,因此它自然也继承了很多用于流畅处理 Eloquent 模型底层数组的方法。

当然,所有集合还可以作为迭代器使用,可以像简单的 PHP 数组一样遍历它们:

$users = App\User::where('active', 1)->get();

foreach ($users as $user) {
    echo $user->name;
}

然而,集合比数组更强大,并且使用更直观的接口链式调用各种映射/过滤操作。例如,我们移除所有未激活的模型并将每个剩下用户的名字聚集到一起:

$users = App\User::all();

$names = $users->reject(function ($user) {
    return $user->active === false;
})
->map(function ($user) {
    return $user->name;
});

尽管大多数 Eloquent 集合方法返回一个新的 Eloquent 集合实例,但是 pluckkeyszipcollapseflattenflip 方法返回一个 集合基类 的实例。同样,如果 map 操作返回一个不包含任何 Eloquent 模型的集合,它也会被自动转换为集合基类。

可用的方法

集合基类

所有 Eloquent 集合都继承自基础的 Laravel 集合 对象;因此,它们会继承集合基类提供的所有强大的方法:

all
average
avg
chunk
collapse
combine
concat
contains
containsStrict
count
crossJoin
dd
diff
diffKeys
dump
each
eachSpread
every
except
filter
first
flatMap
flatten
flip
forget
forPage
get
groupBy
has
implode
intersect
isEmpty
isNotEmpty
keyBy
keys
last
map
mapInto
mapSpread
mapToGroups
mapWithKeys
max
median
merge
min
mode
nth
only
pad
partition
pipe
pluck
pop
prepend
pull
push
put
random
reduce
reject
reverse
search
shift
shuffle
slice
sort
sortBy
sortByDesc
splice
split
sum
take
tap
toArray
toJson
transform
union
unique
uniqueStrict
unless
values
when
where
whereStrict
whereIn
whereInStrict
whereNotIn
whereNotInStrict
zip

自定义集合

如果需要使用具有自己的扩展方法的自定义 Collection 对象,可以在自己的模型上重写 newCollection 方法:

namespace App;

use App\CustomCollection;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 创建一个新的 Eloquent 集合实例
     *
     * @param  array  $models
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function newCollection(array $models = [])
    {
        return new CustomCollection($models);
    }
}

定义 newCollection 方法后,Eloquent 返回对应模型的 Collection 实例时始终会收到一个自定义集合的实例。如果要为应用中每个模型都使用自定义集合,则应该重写所有模型都继承的模型基类上的 newCollection 方法。