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 集合的新實例,但 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 setVisible setHidden toQuery unique
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']);
only($keys)
only
方法返回具有給定主鍵的所有模型
1$users = $users->only([1, 2, 3]);
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();
自訂集合
如果您想在與給定模型互動時使用自訂 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 Model11{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 Model10{11 /**12 * Create a new Eloquent Collection instance.13 *14 * @param array<int, \Illuminate\Database\Eloquent\Model> $models15 * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model>16 */17 public function newCollection(array $models = []): Collection18 {19 return new UserCollection($models);20 }21}
一旦您定義了 newCollection
方法或將 CollectedBy
屬性添加到您的模型中,每當 Eloquent 通常返回 Illuminate\Database\Eloquent\Collection
實例時,您都會收到自訂集合的實例。
如果您想為應用程式中的每個模型使用自訂集合,您應該在應用程式所有模型擴展的基礎模型類別上定義 newCollection
方法。