所有返回多个模型结果的 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;
});虽然大多数 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
contains
diff
except
find
findOrFail
fresh
intersect
load
loadMissing
modelKeys
makeVisible
makeHidden
only
partition
setAppends
setVisible
setHidden
toQuery
unique
withoutAppends
append($attributes)append 方法可用于指示一个属性应被附加用于集合中的每个模型。此方法接受一个属性数组或单个属性:
$users->append('team');
$users->append(['team', 'is_admin']);contains($key, $operator = null, $value = null)该 contains 方法可用于判断给定模型实例是否包含在该集合中。该方法接受主键或模型实例:
$users->contains(1);
$users->contains(User::find(1));diff($items)该 diff 方法返回所有不在给定集合中的模型:
use App\Models\User;
$users = $users->diff(User::whereIn('id', [1, 2, 3])->get());排除($keys)except 方法返回所有不包含给定主键的模型:
$users = $users->except([1, 2, 3]);查找($key)该 find 方法返回其主键与给定键匹配的模型。如果 $key 是一个模型实例,find 将尝试返回一个与该主键匹配的模型。如果 $key 是一个键数组,find 将返回其主键在给定数组中的所有模型:
$users = User::all();
$user = $users->find(1);findOrFail($key)The method returns the model that has a primary key matching the given key or throws an Illuminate\Database\Eloquent\ModelNotFoundException exception if no matching model can be found in the collection:
$users = User::all();
$user = $users->findOrFail(1);fresh($with = [])该 fresh 方法会从数据库中检索集合中每个模型的一个全新实例。此外,任何指定的关联关系都将被预加载:
$users = $users->fresh();
$users = $users->fresh('comments');intersect($items)intersect 方法返回在给定集合中也存在的所有模型:
use App\Models\User;
$users = $users->intersect(User::whereIn('id', [1, 2, 3])->get());load($relations)load 方法会为集合中的所有模型预加载给定的关联关系:
$users->load(['comments', 'posts']);
$users->load('comments.author');
$users->load(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);加载缺失($relations)loadMissing 方法会为集合中的所有模型预加载给定的关系,前提是这些关系尚未加载:
$users->loadMissing(['comments', 'posts']);
$users->loadMissing('comments.author');
$users->loadMissing(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);模型键()该 modelKeys 方法返回集合中所有模型的主键:
$users->modelKeys();
// [1, 2, 3, 4, 5]makeVisible($attributes)makeVisible 方法 使属性可见,这些属性通常在集合中的每个模型上被“隐藏”:
$users = $users->makeVisible(['address', 'phone_number']);隐藏($attributes)makeHidden 方法会 隐藏属性,这些属性通常在集合中的每个模型上都是“可见”的:
$users = $users->makeHidden(['address', 'phone_number']);仅保留($keys)该 only 方法返回所有具有给定主键的模型:
$users = $users->only([1, 2, 3]);分区该 partition 方法返回一个 Illuminate\Support/Collection 的实例,其中包含 Illuminate/Database/Eloquent/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\CollectionsetAppends($attributes)setAppends 方法会临时覆盖集合中每个模型上的所有 追加的属性:
$users = $users->setAppends(['is_admin']);setVisible($attributes)setVisible 方法 [暂时覆盖](/zh-cn/docs/laravel/12.x/eloquent-serialization#temporarily-modifying-attribute-visibility) 集合中每个模型上的所有可见属性:
$users = $users->setVisible(['id', 'name']);setHidden($attributes)setHidden 方法 临时覆盖 集合中每个模型的所有隐藏属性:
$users = $users->setHidden(['email', 'password', 'remember_token']);toQuery()该 toQuery 方法返回一个包含针对集合模型主键的 whereIn 约束的 Eloquent 查询构建器实例:
use App\Models\User;
$users = User::where('status', 'VIP')->get();
$users->toQuery()->update([
'status' => 'Administrator',
]);unique($key = null, $strict = false)The unique method returns all of the unique models in the collection. Any models with the same primary key as another model in the collection are removed:
$users = $users->unique();withoutAppends($attributes)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
{
/**
* Create a new Eloquent Collection instance.
*
* @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 方法,该基础模型类被你的应用程序的所有模型继承。