介绍

所有返回一个以上模型结果的 Eloquent 方法都会返回 php Illuminate\Database\Eloquent\Collection 类的实例,包括通过 php get 方法获取或者通过关联访问的结果。 Eloquent 集合对象扩展了 Laravel 的 基本集合, 所以它很自然地继承了数十种 Eloquent 模型底层方法。可以查看 Laravel 集合文档,了解这些有用的方法!

所有集合还可以作为迭代器使用,可以像使用 PHP 数组一样对它们进行循环:

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

不过,如前所述,集合比数组强大得多,它提供了各种映射/还原操作,可以使用直观的界面进行连锁操作。例如,我们可以删除所有不活动的模型,然后收集每个剩余用户的名字:

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

Eloquent 集合转换
大多数 Eloquent 集合方法都会返回一个 Eloquent 集合的新实例, 而 php collapse, php flatten, php flip, php keys, php pluck, 和 php zip 方法则会返回一个基础集合 实例。 同样, 如果 php map 操作返回的集合不包含任何 Eloquent 模型,它将被转换为基础集合实例。

可用的方法

所有 Eloquent 的集合都继承了 Laravel collection 对象;因此, 他们也继承了所有集合基类提供的强大的方法。

另外, php Illuminate\Database\Eloquent\Collection 类提供了一套上层的方法来帮你管理你的模型集合。大多数方法返回 php Illuminate\Database\Eloquent\Collection 实例;然而,也会有一些方法, 例如 php modelKeys, 它们会返回 php Illuminate\Support\Collection 类的实例。

append
contains
diff
except
find
fresh
intersect
load
loadMissing
modelKeys
makeVisible
makeHidden
only
setVisible
setHidden
toQuery
unique

php append($attributes)
可以使用 php append 方法来为集合中的模型追加属性。 该方法接受一个数组追加属性或追加单个属性:

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

php contains($key, $operator = null, $value = null)
php contains 方法可用于判断集合中是否包含指定的模型实例。这个方法接收一个主键或者模型实例:

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

php diff($items)
php diff 方法返回不在给定集合中的所有模型:

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

php except($keys)
php except 方法返回给定主键外的所有模型:

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

php find($key)
php find 方法查找给定主键的模型。如果 php $key 是一个模型实例, php find 将会尝试返回与主键匹配的模型。 如果 php $key 是一个关联数组, php find 将返回所有数组主键匹配的模型:

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

php fresh($with = [])
php fresh 方法用于从数据库中检索集合中每个模型的新实例。此外,还将预加载任何指定的关联关系:

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

php intersect($items)
php intersect 方法返回给定集合与当前模型的交集:

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

php load($relations)
php load 方法为集合中的所有模型加载给定关联关系:

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

php loadMissing($relations)
如果尚未加载关联关系,则 php loadMissing 方法将加载集合中所有模型的给定关联关系:

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

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

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

php makeVisible($attributes)
php makeVisible 方法针对集合中平常「隐藏」的属性进行模型隐藏属性可见 :

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

php makeHidden($attributes)
php makeHidden 方法针对集合中平常「可见」的属性进行模型属性隐藏 :

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

php only($keys)
php only 方法返回具有给定主键的所有模型:

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

php setVisible($attributes)
php setVisible 方法临时覆盖集合中每个模型的所有可见属性:

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

php setHidden($attributes)
php setHidden 方法临时覆盖集合中每个模型的所有隐藏属性:

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

php toQuery()
php toQuery 方法返回一个 Eloquent 查询生成器实例,该实例包含集合模型主键上的 php whereIn 约束:

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

php unique($key = null, $strict = false)
php unique 方法返回集合中所有不重复的模型,若模型在集合中存在相同类型且相同主键的另一模型,该模型将被从集合中删除:

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

自定义集合

如果你想在操作某个模型时使用自定义的 php Collection 对象,你可以在模型上定义一个 php newCollection 方法:

  1. <?php
  2. namespace App\Models;
  3. use App\Support\UserCollection;
  4. use Illuminate\Database\Eloquent\Collection;
  5. use Illuminate\Database\Eloquent\Model;
  6. class User extends Model
  7. {
  8. /**
  9. * 创建一个新的合集实例。
  10. *
  11. * @param array<int, \Illuminate\Database\Eloquent\Model> $models
  12. * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model>
  13. */
  14. public function newCollection(array $models = []): Collection
  15. {
  16. return new UserCollection($models);
  17. }
  18. }

一旦定义了 php newCollection 方法,每当 Eloquent 返回一个 php Illuminate\Database\Eloquent\Collection 实例时,你将得到一个你的自定义集合实例。如果你想为应用程序中的所有模型使用自定义集合,你应该在所有应用程序模型都继承的基础模型类上定义 php newCollection 方法。