跳至内容

Eloquent:集合

介绍

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

所有集合也可用作迭代器,允许您循环它们,就像它们是简单的 PHP 数组一样:

1use App\Models\User;
2 
3$users = User::where('active', 1)->get();
4 
5foreach ($users as $user) {
6 echo $user->name;
7}

然而,如前所述,集合比数组功能强大得多,并且提供了各种 map / reduce 操作,可以通过直观的界面进行链式调用。例如,我们可以删除所有不活跃的模型,然后收集每个剩余用户的名字:

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

Eloquent Collection 转换

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

可用方法

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

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

append($attributes)

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

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

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

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

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

diff($items)

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

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

except($keys)

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

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

find($key)

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

1$users = User::all();
2 
3$user = $users->find(1);

findOrFail($key)

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

1$users = User::all();
2 
3$user = $users->findOrFail(1);

fresh($with = [])

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

1$users = $users->fresh();
2 
3$users = $users->fresh('comments');

intersect($items)

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

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

load($relations)

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

1$users->load(['comments', 'posts']);
2 
3$users->load('comments.author');
4 
5$users->load(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);

loadMissing($relations)

如果关系尚未加载,则该loadMissing方法将预先加载集合中所有模型的给定关系:

1$users->loadMissing(['comments', 'posts']);
2 
3$users->loadMissing('comments.author');
4 
5$users->loadMissing(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);

modelKeys()

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

1$users->modelKeys();
2 
3// [1, 2, 3, 4, 5]

makeVisible($attributes)

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

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

makeHidden($attributes)

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

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

only($keys)

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

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

partition

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

1$partition = $users->partition(fn ($user) => $user->age > 18);
2 
3dump($partition::class); // Illuminate\Support\Collection
4dump($partition[0]::class); // Illuminate\Database\Eloquent\Collection
5dump($partition[1]::class); // Illuminate\Database\Eloquent\Collection

setVisible($attributes)

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

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

setHidden($attributes)

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

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

toQuery()

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

1use App\Models\User;
2 
3$users = User::where('status', 'VIP')->get();
4 
5$users->toQuery()->update([
6 'status' => 'Administrator',
7]);

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

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

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

定制系列

如果您想Collection在与给定模型交互时使用自定义对象,您可以将CollectedBy属性添加到模型中:

1<?php
2 
3namespace App\Models;
4 
5use App\Support\UserCollection;
6use Illuminate\Database\Eloquent\Attributes\CollectedBy;
7use Illuminate\Database\Eloquent\Model;
8 
9#[CollectedBy(UserCollection::class)]
10class User extends Model
11{
12 // ...
13}

或者,您可以newCollection在模型上定义一个方法:

1<?php
2 
3namespace App\Models;
4 
5use App\Support\UserCollection;
6use Illuminate\Database\Eloquent\Collection;
7use Illuminate\Database\Eloquent\Model;
8 
9class User extends Model
10{
11 /**
12 * Create a new Eloquent Collection instance.
13 *
14 * @param array<int, \Illuminate\Database\Eloquent\Model> $models
15 * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model>
16 */
17 public function newCollection(array $models = []): Collection
18 {
19 return new UserCollection($models);
20 }
21}

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

如果您希望对应用程序中的每个模型使用自定义集合,则应该newCollection在由所有应用程序模型扩展的基本模型类上定义该方法。