集合
简介
所有返回多个模型结果的 Eloquent 方法都会返回 Illuminate\Database\Eloquent\Collection 类的实例,包括通过 get 方法检索的结果或通过关系访问的结果。Eloquent 集合对象继承了 Laravel 的基础集合,因此它天然继承了数十种用于流畅操作底层 Eloquent 模型数组的方法。请务必查阅 Laravel 集合文档以了解所有这些实用方法!
所有集合还可以作为迭代器使用,允许你像遍历简单的 PHP 数组一样遍历它们:
use App\Models\User;
$users = User::where('active', 1)->get();
foreach ($users as $user) {
echo $user->name;
}
然而,如前所述,集合比数组强大得多,它暴露了各种 map / reduce 操作,可以使用直观的接口进行链式调用。例如,我们可以移除所有未激活的模型,然后收集每个剩余用户的名字:
$names = User::all()->reject(function (User $user) {
return $user->active === false;
})->map(function (User $user) {
return $user->name;
});
典型业务场景:
- 电商订单管理:从数据库获取用户的全部订单集合后,使用
reject过滤已取消订单、map提取金额、sum统计消费总额,全程链式操作无需手动循环 - 后台批量审核:管理员选中一批文章,通过集合的
partition方法按审核状态拆分为「已通过」和「待审核」两组,分别执行不同逻辑 - API 响应字段控制:对外暴露用户列表时,使用
makeHidden批量隐藏手机号和邮箱,或makeVisible临时显示管理字段,无需逐个模型处理 - 数据去重与对比:同步第三方平台数据时,使用
diff找出本地缺失的记录、intersect确认已存在的记录、unique去除重复导入 - 延迟加载优化:列表页渲染后再通过
loadMissing按需补充关联数据,避免初始查询过于臃肿 - 自定义集合扩展:为项目定义专属的
OrderCollection,封装「按金额排序」「按状态分组」等业务方法,让控制器代码更简洁
Eloquent 集合转换
虽然大多数 Eloquent 集合方法返回 Eloquent 集合的新实例,但 collapse、flatten、flip、keys、pluck 和 zip 方法返回基础集合实例。同样,如果 map 操作返回的集合不包含任何 Eloquent 模型,它将被转换为基础集合实例。
可用方法
所有 Eloquent 集合都继承了基础的 Laravel 集合对象;因此,它们继承了基础集合类提供的所有强大方法。
此外,Illuminate\Database\Eloquent\Collection 类提供了一组超集方法来帮助管理你的模型集合。大多数方法返回 Illuminate\Database\Eloquent\Collection 实例;然而,一些方法,如 modelKeys,返回 Illuminate\Support\Collection 实例。
append()
append 方法可用于指示应为集合中的每个模型追加属性。此方法接受属性数组或单个属性:
$users->append('team');
$users->append(['team', 'is_admin']);
contains()
contains 方法可用于确定集合中是否包含给定的模型实例。此方法接受主键或模型实例:
$users->contains(1);
$users->contains(User::find(1));
diff()
diff 方法返回不存在于给定集合中的所有模型:
use App\Models\User;
$users = $users->diff(User::whereIn('id', [1, 2, 3])->get());
except()
except 方法返回不具有给定主键的所有模型:
$users = $users->except([1, 2, 3]);
find()
find 方法返回主键与给定键匹配的模型。如果 $key 是模型实例,find 将尝试返回主键匹配的模型。如果 $key 是键数组,find 将返回主键在给定数组中的所有模型:
$users = User::all();
$user = $users->find(1);
findOrFail()
findOrFail 方法返回主键与给定键匹配的模型,如果在集合中找不到匹配的模型,则抛出 Illuminate\Database\Eloquent\ModelNotFoundException 异常:
$users = User::all();
$user = $users->findOrFail(1);
fresh()
fresh 方法从数据库中检索集合中每个模型的最新实例。此外,任何指定的关系将被预加载:
$users = $users->fresh();
$users = $users->fresh('comments');
intersect()
intersect 方法返回同时存在于给定集合中的所有模型:
use App\Models\User;
$users = $users->intersect(User::whereIn('id', [1, 2, 3])->get());
load()
load 方法为集合中的所有模型预加载给定的关系:
$users->load(['comments', 'posts']);
$users->load('comments.author');
$users->load(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);
loadMissing()
loadMissing 方法在关系尚未加载的情况下,为集合中的所有模型预加载给定的关系:
$users->loadMissing(['comments', 'posts']);
$users->loadMissing('comments.author');
$users->loadMissing(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);
modelKeys()
modelKeys 方法返回集合中所有模型的主键:
$users->modelKeys();
// [1, 2, 3, 4, 5]
makeVisible()
makeVisible 方法使属性可见,这些属性通常在集合中的每个模型上是「隐藏」的:
$users = $users->makeVisible(['address', 'phone_number']);
makeHidden()
makeHidden 方法隐藏属性,这些属性通常在集合中的每个模型上是「可见」的:
$users = $users->makeHidden(['address', 'phone_number']);
mergeVisible()
mergeVisible 方法在保留现有可见属性的同时使额外的属性可见:
$users = $users->mergeVisible(['middle_name']);
mergeHidden()
mergeHidden 方法在保留现有隐藏属性的同时隐藏额外的属性:
$users = $users->mergeHidden(['last_login_at']);
only()
only 方法返回具有给定主键的所有模型:
$users = $users->only([1, 2, 3]);
partition()
partition 方法返回一个包含 Illuminate\Database\Eloquent\Collection 集合实例的 Illuminate\Support\Collection 实例:
$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()
setAppends 方法临时覆盖集合中每个模型上的所有追加属性:
$users = $users->setAppends(['is_admin']);
setVisible()
setVisible 方法临时覆盖集合中每个模型上的所有可见属性:
$users = $users->setVisible(['id', 'name']);
setHidden()
setHidden 方法临时覆盖集合中每个模型上的所有隐藏属性:
$users = $users->setHidden(['email', 'password', 'remember_token']);
toQuery()
toQuery 方法返回一个 Eloquent 查询构建器实例,其中包含对集合模型主键的 whereIn 约束:
use App\Models\User;
$users = User::where('status', 'VIP')->get();
$users->toQuery()->update([
'status' => 'Administrator',
]);
unique()
unique 方法返回集合中所有唯一的模型。任何与集合中另一个模型具有相同主键的模型都将被移除:
$users = $users->unique();
withoutAppends()
withoutAppends 方法临时移除集合中每个模型上的所有追加属性:
$users = $users->withoutAppends();
自定义集合
如果你想在操作给定模型时使用自定义的 Collection 对象,可以在模型上添加 CollectedBy 属性:
<?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
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
{
$collection = new UserCollection($models);
if (Model::isAutomaticallyEagerLoadingRelationships()) {
$collection->withRelationshipAutoloading();
}
return $collection;
}
}
一旦你定义了 newCollection 方法或在模型上添加了 CollectedBy 属性,每当 Eloquent 通常返回 Illuminate\Database\Eloquent\Collection 实例时,你都将收到自定义集合的实例。
如果你想为应用中的每个模型使用自定义集合,你应该在所有模型继承的基础模型类上定义 newCollection 方法。