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) {
    return $user->active === false;
})->map(function ($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)

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

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 是一个键数组,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 方法为集合中的所有模型预加载给定的关系:

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

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

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

loadMissing($relations)

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

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)

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

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

setVisible($attributes)

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

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

setHidden($attributes)

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

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

toQuery()

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

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\Model;

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

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