跳到主要內容

Eloquent 集合

📝 此頁面為 Laravel 官方文檔的繁體中文翻譯。查看原始英文版本

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 集合的新實例,但 collapseflattenflipkeyspluckzip 方法返回基礎集合實例。同樣地,如果 map 操作返回一個不包含任何 Eloquent 模型的集合,它將被轉換為基礎集合實例。

可用方法

所有 Eloquent 集合都擴展了基礎 Laravel 集合物件;因此,它們繼承了基礎集合類別提供的所有強大方法。

此外,Illuminate\Database\Eloquent\Collection 類別提供了一組超集方法來協助管理您的模型集合。大多數方法返回 Illuminate\Database\Eloquent\Collection 實例;但是,一些方法(如 modelKeys)返回 Illuminate\Support\Collection 實例。

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

findOrFail($key) {.collection-method}

findOrFail 方法返回具有與給定鍵匹配的主鍵的模型,如果在集合中找不到匹配的模型,則拋出 Illuminate\Database\Eloquent\ModelNotFoundException 異常:

$users = User::all();

$user = $users->findOrFail(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']);

mergeVisible($attributes) {.collection-method}

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

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

mergeHidden($attributes) {.collection-method}

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

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

only($keys) {.collection-method}

only 方法返回所有具有給定主鍵的模型:

$users = $users->only([1, 2, 3]);

partition {.collection-method}

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\Collection

setAppends($attributes) {.collection-method}

setAppends 方法暫時覆蓋集合中每個模型上的所有追加屬性

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

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

withoutAppends() {.collection-method}

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 集合實例。
     *
     * @param  array  $models
     * @return \Illuminate\Database\Eloquent\Collection
     */
    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 方法。