Skip to content
全部文档

Eloquent:集合

简介

所有返回多个模型结果的 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;
}

不过如前所述,集合远比数组强大,并提供多种可用直观接口链式调用的 map / reduce 操作。例如,我们可以先移除所有未激活的模型,再收集剩余用户的名字:

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

Eloquent 集合转换

虽然大多数 Eloquent 集合方法会返回新的 Eloquent 集合实例,但 collapseflattenflipkeyspluckzip 方法会返回基础集合实例。同样,若 map 操作返回的集合不包含任何 Eloquent 模型,也会被转换为基础集合实例。

可用方法

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

此外,Illuminate\Database\Eloquent\Collection 类还提供了一组额外方法,用于管理模型集合。大多数方法返回 Illuminate\Database\Eloquent\Collection 实例;但像 modelKeys 等方法会返回 Illuminate\Support\Collection 实例。

append($attributes) {.collection-method .first-collection-method}

append 方法可用于指定集合中每个模型都应追加某个属性。该方法接受属性数组或单个属性:

$users->append('team');

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

contains($key, $operator = null, $value = null) {.collection-method}

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

$users->contains(1);

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

diff($items) {.collection-method}

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

use App\Models\User;

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

except($keys) {.collection-method}

except 方法返回主键不在给定列表中的所有模型:

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

find($key) {.collection-method}

find 方法返回主键与给定键匹配的模型。若 $key 是模型实例,find 会尝试返回主键匹配的模型。若 $key 是键数组,find 会返回主键位于该数组中的所有模型:

$users = User::all();

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

findOrFail($key) {.collection-method}

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

$users = User::all();

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

fresh($with = []) {.collection-method}

fresh 方法会从数据库重新获取集合中每个模型的全新实例。此外,指定的关联会被预加载:

$users = $users->fresh();

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

intersect($items) {.collection-method}

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

use App\Models\User;

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

load($relations) {.collection-method}

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

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

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

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

loadMissing($relations) {.collection-method}

若关联尚未加载,loadMissing 方法会为集合中的所有模型预加载给定关联:

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

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

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

modelKeys() {.collection-method}

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

$users->modelKeys();

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

makeVisible($attributes) {.collection-method}

makeVisible 方法会将集合中每个模型上通常「隐藏」的属性设为可见

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

makeHidden($attributes) {.collection-method}

makeHidden 方法会将集合中每个模型上通常「可见」的属性隐藏

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

only($keys) {.collection-method}

only 方法返回主键位于给定列表中的所有模型:

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

setVisible($attributes) {.collection-method}

setVisible 方法会临时覆盖集合中每个模型上的全部可见属性:

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

setHidden($attributes) {.collection-method}

setHidden 方法会临时覆盖集合中每个模型上的全部隐藏属性:

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

toQuery() {.collection-method}

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

use App\Models\User;

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

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

unique($key = null, $strict = false) {.collection-method}

unique 方法返回集合中的全部唯一模型。与集合中另一模型具有相同主键的模型会被移除:

$users = $users->unique();

自定义集合

若希望在与某个模型交互时使用自定义 Collection 对象,可在模型上添加 CollectedBy 属性:

php
<?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
<?php

namespace App\Models;

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

class User extends Model
{
    /**
     * Create a new Eloquent Collection instance.
     *
     * @param  array<int, \Illuminate\Database\Eloquent\Model>  $models
     * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model>
     */
    public function newCollection(array $models = []): Collection
    {
        return new UserCollection($models);
    }
}

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

若希望应用中每个模型都使用自定义集合,应在所有应用模型继承的基础模型类上定义 newCollection 方法。