跳轉至內容

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 集合轉換

雖然大多數 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']);

mergeVisible($attributes)

mergeVisible 方法在保留現有可見屬性的同時,使額外的屬性可見

1$users = $users->mergeVisible(['middle_name']);

mergeHidden($attributes)

mergeHidden 方法在保留現有隱藏屬性的同時,隱藏額外的屬性

1$users = $users->mergeHidden(['last_login_at']);

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

setAppends($attributes)

setAppends 方法臨時覆蓋集合中每個模型的 追加屬性

1$users = $users->setAppends(['is_admin']);

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();

withoutAppends()

withoutAppends 方法臨時移除集合中每個模型的所有 追加屬性

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

自定義集合

如果您希望在與給定模型互動時使用自定義 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 $collection = new UserCollection($models);
20 
21 if (Model::isAutomaticallyEagerLoadingRelationships()) {
22 $collection->withRelationshipAutoloading();
23 }
24 
25 return $collection;
26 }
27}

一旦您定義了 newCollection 方法或將 CollectedBy 屬性新增到您的模型中,每當 Eloquent 通常返回 Illuminate\Database\Eloquent\Collection 例項時,您都將收到自定義集合的例項。

如果您希望為應用程式中的每個模型使用自定義集合,則應在所有應用程式模型所繼承的基礎模型類上定義 newCollection 方法。