简介

所有返回多个模型结果的 Eloquent 方法都会返回 Illuminate\Database\Eloquent\Collection 类的实例,包括通过 get 方法检索到的结果,或者通过关系访问到的结果。Eloquent 集合对象扩展了 Laravel 的基础集合,因此它自然继承了数十种方法,可流畅地操作底层的 Eloquent 模型数组。请务必查阅 Laravel 集合文档,以了解这些实用方法!

所有集合也可作为迭代器使用,允许你像遍历简单 PHP 数组一样遍历它们:

use App\Models\User;

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

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

然而,正如前面所提到的,集合比数组功能强大得多,它提供了多种映射/规约操作,可以通过直观的接口进行链式调用。例如,我们可以移除所有未激活的模型,然后收集每个剩余用户的姓氏:

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

Eloquent 集合转换

虽然大多数 Eloquent 集合方法会返回一个新的 Eloquent 集合实例,但 collapse、flatten、flip、keys、pluck 和 zip 方法会返回基础集合实例。同样,如果 map 操作返回的集合不包含任何 Eloquent 模型,它将被转换为基础集合实例。

可用方法

所有 Eloquent 集合都扩展了基础的Laravel 集合对象;因此,它们继承了基础集合类提供的所有强大方法。

此外,Illuminate\Database\Eloquent\Collection 类还提供了一组额外的方法,以帮助管理你的模型集合。大多数方法会返回 Illuminate\Database\Eloquent\Collection 实例;然而,像 pluck 这样的一些方法会返回 Illuminate\Support\Collection 实例。

appendcontainsdiffexceptfindfindOrFailfreshintersectloadloadMissingmodelKeysmakeVisiblemakeHiddenmergeVisiblemergeHiddenonlypartitionsetAppendssetVisiblesetHiddentoQueryuniquewithoutAppends

append($attributes)

append 方法可用于指示应为集合中的每个模型附加某个属性。此方法接受一个属性数组或单个属性:

$users->append('team');

$users->append(['team', 'is_admin']);

contains($key, $operator = null, $value = null)

contains 方法可用于判断集合中是否包含指定的模型实例。此方法接受主键或模型实例:

$users->contains(1);

$users->contains(User::find(1));

diff($items)

diff 方法返回不在给定集合中的所有模型:

use App\Models\User;

$users = $users->diff(User::whereIn('id', [1, 2, 3])->get());

except($keys)

except 方法返回不具有给定主键的所有模型:

$users = $users->except([1, 2, 3]);

find($key)

find 方法返回主键与给定键匹配的模型。如果 $key 是模型实例,find 将尝试返回主键匹配的模型。如果 $key 是键的数组,find 将返回所有主键在给定数组中的模型:

$users = User::all();

$user = $users->find(1);

findOrFail($key)

findOrFail 方法返回主键与给定键匹配的模型,如果在集合中找不到匹配的模型,则抛出 Illuminate\Database\Eloquent\ModelNotFoundException 异常:

$users = User::all();

$user = $users->findOrFail(1);

fresh($with = [])

fresh 方法从数据库中检索集合中每个模型的新实例。此外,任何指定的关系都会被预加载:

$users = $users->fresh();

$users = $users->fresh('comments');

intersect($items)

intersect 方法返回也在给定集合中的所有模型:

use App\Models\User;

$users = $users->intersect(User::whereIn('id', [1, 2, 3])->get());

load($relations)

load 方法为集合中的所有模型预加载给定的关系:

$users->load(['comments', 'posts']);

$users->load('comments.author');

$users->load(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);

loadMissing($relations)

loadMissing 方法会为集合中的所有模型预加载给定的关系,前提是这些关系尚未加载:

$users->loadMissing(['comments', 'posts']);

$users->loadMissing('comments.author');

$users->loadMissing(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);

modelKeys()

modelKeys 方法返回集合中所有模型的主键:

$users->modelKeys();

// [1, 2, 3, 4, 5]

makeVisible($attributes)

makeVisible 方法使属性可见,这些属性通常在集合中的每个模型上是“隐藏”的:

$users = $users->makeVisible(['address', 'phone_number']);

makeHidden($attributes)

makeHidden 方法隐藏属性,这些属性通常在集合中的每个模型上是“可见”的:

$users = $users->makeHidden(['address', 'phone_number']);

mergeVisible($attributes)

mergeVisible 方法使额外的属性可见,同时保留现有的可见属性:

$users = $users->mergeVisible(['middle_name']);

mergeHidden($attributes)

mergeHidden 方法隐藏额外的属性,同时保留现有的隐藏属性:

$users = $users->mergeHidden(['last_login_at']);

only($keys)

only 方法返回具有给定主键的所有模型:

$users = $users->only([1, 2, 3]);

partition

partition 方法返回一个 Illuminate\Support\Collection 实例,其中包含 Illuminate\Database\Eloquent\Collection 集合实例:

$partition = $users->partition(fn ($user) => $user->age > 18);

dump($partition::class);    // Illuminate\Support\Collection
dump($partition[0]::class); // Illuminate\Database\Eloquent\Collection
dump($partition[1]::class); // Illuminate\Database\Eloquent\Collection

setAppends($attributes)

setAppends 方法会临时覆盖集合中每个模型的所有附加属性:

$users = $users->setAppends(['is_admin']);

setVisible($attributes)

setVisible 方法临时覆盖集合中每个模型的所有可见属性:

$users = $users->setVisible(['id', 'name']);

setHidden($attributes)

setHidden 方法临时覆盖集合中每个模型的所有隐藏属性:

$users = $users->setHidden(['email', 'password', 'remember_token']);

toQuery()

toQuery 方法会返回一个 Eloquent 查询构造器实例,其中包含针对集合模型主键的 whereIn 约束:

use App\Models\User;

$users = User::where('status', 'VIP')->get();

$users->toQuery()->update([
    'status' => 'Administrator',
]);

unique($key = null, $strict = false)

unique 方法会返回集合中所有唯一的模型。任何主键与集合中其他模型相同的模型都会被移除:

$users = $users->unique();

withoutAppends()

withoutAppends 方法会临时移除集合中每个模型上已追加的属性:

$users = $users->withoutAppends();

自定义集合

当你在与给定模型交互时,如果想使用自定义的 Collection 对象,可以为模型添加 CollectedBy 特性:

<?php

namespace App\Models;

use App\Support\UserCollection;
use Illuminate\Database\Eloquent\Attributes\CollectedBy;
use Illuminate\Database\Eloquent\Model;

#[CollectedBy(UserCollection::class)]
class User extends Model
{
    // ...
}

或者,你可以在模型中定义 newCollection 方法:

<?php

namespace App\Models;

use App\Support\UserCollection;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 创建一个新的 Eloquent Collection 实例。
     *
     * @param  array<int, \Illuminate\Database\Eloquent\Model>  $models
     * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model>
     */
    public function newCollection(array $models = []): Collection
    {
        $collection = new UserCollection($models);

        if (Model::isAutomaticallyEagerLoadingRelationships()) {
            $collection->withRelationshipAutoloading();
        }

        return $collection;
    }
}

一旦定义了 newCollection 方法或为模型添加了 CollectedBy 特性,每当 Eloquent 通常会返回 Illuminate\Database\Eloquent\Collection 实例时,你都会收到自定义集合的实例。

如果想为应用中的所有模型使用自定义集合,应在所有应用模型所继承的基础模型类中定义 newCollection 方法。