Eloquent 集合
Eloquent:集合
介绍
所有以多个模型为查询结果的 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 集合方法返回一个新的 Eloquent 集合实例的前提下,collapse,flatten,flip, keys,pluck,以及 zip 方法返回一个基础集合类的实例。 如果一个 map 方法返回了一个不包含任何模型的 Eloquent 集合,它也会被转换成一个基础集合实例。
可用的方法
所有 Eloquent 的集合都继承了 Laravel collection 对象;因此, 他们也继承了所有集合基类提供的强大的方法。
另外, Illuminate\Database\Eloquent\Collection 类提供了一套上层的方法来帮你管理你的模型集合。大多数方法返回 Illuminate\Database\Eloquent\Collection 实例;然而,也会有一些方法, 例如 modelKeys, 它们会返回基于 Illuminate\Support\Collection 类的实例。
append
contains
diff
except
find
fresh
intersect
load
loadMissing
modelKeys
makeVisible
makeHidden
only
setVisible
setHidden
toQuery
unique
append($attributes) {.collection-method .first-collection-method}
可以使用append方法来为集合中的模型追加属性。 可以是数组或单个属性追加:
$users->append('team');
$users->append(['team', 'is_admin']);
contains($key, $operator = null, $value = null) {.collection-method}
contains 方法可用于判断集合中是否包含指定的模型实例。这个方法接收一个主键或者模型实例:
$users->contains(1);
$users->contains(User::find(1));
diff($items) {.collection-method}
diff 方法返回不在给定集合中的所有模型:
use App\Models\User;
$users = $users->diff(User::whereIn('id', [1, 2, 3])->get());
except($keys) {.collection-method}
except 方法返回给定主键外的所有模型:
$users = $users->except([1, 2, 3]);
find($key) {.collection-method}
find 方法查找给定主键的模型。如果 $key 是一个模型实例, find 将会尝试返回与主键匹配的模型。 如果 $key 是一个关联数组, find 将返回所有数组主键匹配的模型:
$users = User::all();
$user = $users->find(1);
fresh($with = []) {.collection-method}
fresh 方法用于从数据库中检索集合中每个模型的新实例。此外,还将加载任何指定的关联关系:
$users = $users->fresh();
$users = $users->fresh('comments');
intersect($items) {.collection-method}
intersect 方法返回给定集合与当前模型的交集:
use App\Models\User;
$users = $users->intersect(User::whereIn('id', [1, 2, 3])->get());
load($relations) {.collection-method}
load 方法为集合中的所有模型加载给定关联关系:
$users->load(['comments', 'posts']);
$users->load('comments.author');
$users->load(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);
loadMissing($relations) {.collection-method}
如果尚未加载关联关系,则 loadMissing 方法将加载集合中所有模型的给定关联关系:
$users->loadMissing(['comments', 'posts']);
$users->loadMissing('comments.author');
$users->loadMissing(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);
modelKeys() {.collection-method}
modelKeys 方法返回集合中所有模型的主键:
$users->modelKeys();
// [1, 2, 3, 4, 5]
makeVisible($attributes) {.collection-method}
makeVisible 方法使模型上的隐藏属性可见 :
$users = $users->makeVisible(['address', 'phone_number']);
makeHidden($attributes) {.collection-method}
makeHidden 方法隐藏模型属性 :
$users = $users->makeHidden(['address', 'phone_number']);
only($keys) {.collection-method}
only 方法返回具有给定主键的所有模型:
$users = $users->only([1, 2, 3]);
setVisible($attributes) {.collection-method}
setVisible方法临时覆盖集合中每个模型的所有可见属性:
$users = $users->setVisible(['id', 'name']);
setHidden($attributes) {.collection-method}
setHidden方法临时覆盖集合中每个模型的所有隐藏属性:
$users = $users->setHidden(['email', 'password', 'remember_token']);
toQuery() {.collection-method}
toQuery 方法返回一个 Eloquent 查询生成器实例,该实例包含集合模型主键上的 whereIn 约束:
use App\Models\User;
$users = User::where('status', 'VIP')->get();
$users->toQuery()->update([
'status' => 'Administrator',
]);
unique($key = null, $strict = false) {.collection-method}
unique 方法返回集合中所有不重复的模型,若模型在集合中存在相同类型且相同主键的另一模型,该模型将被删除:
$users = $users->unique();
自定义集合
如果你想在与模型交互时使用一个自定义的 Collection 对象,你可以通过在模型中定义 newCollection 方法来实现:
<?php
namespace App\Models;
use App\Support\UserCollection;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* 创建新的Elquent 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
{
return new UserCollection($models);
}
}
一旦在模型中定义了一个 newCollection 方法,每当 Eloquent 需要返回一个 Illuminate\Database\Eloquent\Collection 实例的时候,将会返回自定义集合的实例取代之。如果你想使每一个模型都使用自定义的集合,可以在一个模型基类中定义一个 newCollection 方法,然后让其它模型派生于此基类。
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
Laravel 10 中文文档
关于 LearnKu
推荐文章: