Skip to content

Eloquent:集合

简介

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

所有集合还充当迭代器,允许你像遍历简单的 PHP 数组一样遍历它们:

php
use App\Models\User;

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

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

但是,如前所述,集合比数组强大得多,并且公开了各种可以使用直观接口链式调用的 map / reduce 操作。例如,我们可以移除所有不活跃的模型,然后收集每个剩余用户的名字:

php
$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 方法可用于指示集合中的每个模型应追加某个属性。此方法接受属性数组或单个属性:

php
$users->append('team');

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

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

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

php
$users->contains(1);

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

diff($items) {.collection-method}

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

php
use App\Models\User;

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

except($keys) {.collection-method}

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

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

find($key) {.collection-method}

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

php
$users = User::all();

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

findOrFail($key) {.collection-method}

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

php
$users = User::all();

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

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

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

php
$users = $users->fresh();

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

intersect($items) {.collection-method}

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

php
use App\Models\User;

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

load($relations) {.collection-method}

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

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

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

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

loadMissing($relations) {.collection-method}

loadMissing 方法在关联关系尚未加载的情况下,为集合中的所有模型预加载给定的关联关系:

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

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

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

modelKeys() {.collection-method}

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

php
$users->modelKeys();

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

makeVisible($attributes) {.collection-method}

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

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

makeHidden($attributes) {.collection-method}

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

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

mergeVisible($attributes) {.collection-method}

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

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

mergeHidden($attributes) {.collection-method}

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

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

only($keys) {.collection-method}

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

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

partition {.collection-method}

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

php
$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) {.collection-method}

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

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

setVisible($attributes) {.collection-method}

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

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

setHidden($attributes) {.collection-method}

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

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

toQuery() {.collection-method}

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

php
use App\Models\User;

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

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

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

unique 方法返回集合中所有唯一的模型。与集合中另一个模型具有相同主键的任何模型将被移除:

php
$users = $users->unique();

withoutAppends() {.collection-method}

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

php
$users = $users->withoutAppends();

自定义集合

如果你想在与给定模型交互时使用自定义的 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
    {
        $collection = new UserCollection($models);

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

        return $collection;
    }
}

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

如果你想为应用程序中的每个模型使用自定义集合,你应该在一个基础模型类上定义 newCollection 方法,该基础模型类被你应用程序的所有模型继承。