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 集合对象;因此,它们继承了 Base Collection 类提供的所有强大方法。

此外,该 Illuminate\Database\Eloquent\Collection 类还提供了一组超集方法来帮助管理模型集合。大多数方法返回 Illuminate\Database\Eloquent\Collection 实例; 但是,某些方法(如 modelKeys)会返回 Illuminate\Support\Collection 实例。

append($attributes)

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

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

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

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

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

php
    $users->contains(1);

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

diff($items)

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

php
    use App\Models\User;

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

except($keys)

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

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

find($key)

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

php
    $users = User::all();

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

fresh($with = [])

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

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

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

intersect($items)

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

php
    use App\Models\User;

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

load($relations)

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

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

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

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

loadMissing($relations)

loadMissing 方法 eager 加载集合中所有模型的给定关系(如果尚未加载这些关系):

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

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

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

modelKeys()

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

php
    $users->modelKeys();

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

makeVisible($attributes)

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

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

makeHidden($attributes)

makeHidden 方法隐藏了通常在集合中的每个模型上 “可见” 的属性

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

only($keys)

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

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

setVisible($attributes)

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

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

setHidden($attributes)

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

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

toQuery()

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

php
    use App\Models\User;

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

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

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

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

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

自定义集合

如果你想在与给定模型交互时使用自定义 Collection 对象,你可以在模型上定义一个 newCollection 方法:

php
    <?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
        {
            return new UserCollection($models);
        }
    }

一旦你定义了一个 newCollection 方法,你就会在 Eloquent 通常返回 Illuminate\Database\Eloquent\Collection 实例的时候收到一个自定义集合的实例。如果你想为应用程序中的每个模型使用自定义集合,你应该在由应用程序的所有模型扩展的基模型类上定义 newCollection 方法。