Readouble

Laravel 8.x Eloquent:コレクション

イントロダクションIntroduction

getメソッドで取得した結果や、リレーションによりアクセスした結果など、結果として複数のモデルを返すEloquentメソッドはすべて、Illuminate\Database\Eloquent\Collectionクラスのインスタンスを返します。EloquentコレクションオブジェクトはLaravelの基本的なコレクションを拡張しているため、基になるEloquentモデルの配列を流暢に操作するため使用する数十のメソッドを自然と継承します。これらの便利な方法についてすべて学ぶために、Laravelコレクションのドキュメントは必ず確認してください!All Eloquent methods that return more than one model result will return instances of the Illuminate\Database\Eloquent\Collection class, including results retrieved via the get method or accessed via a relationship. The Eloquent collection object extends Laravel's base collection[/docs/{{version}}/collections], so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models. Be sure to review the Laravel collection documentation to learn all about these helpful methods!

すべてのコレクションはイテレーターとしても機能し、単純なPHP配列であるかのようにループで使えます。All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:

use App\Models\User;

$users = User::where('active', 1)->get();

foreach ($users as $user) {
    echo $user->name;
}

ただし、前述のようにコレクションは配列よりもはるかに強力であり、直感的なインターフェイスを使用してチェーンする可能性を持つさまざまなマップ/リデュース操作を用意しています。たとえば、非アクティブなモデルをすべて削除してから、残りのユーザーの名を収集する場面を考えましょう。However, as previously mentioned, collections are much more powerful than arrays and expose a variety of map / reduce operations that may be chained using an intuitive interface. For example, we may remove all inactive models and then gather the first name for each remaining user:

$names = User::all()->reject(function ($user) {
    return $user->active === false;
})->map(function ($user) {
    return $user->name;
});

Eloquentコレクションの変換Eloquent Collection Conversion

ほとんどのEloquentコレクションメソッドはEloquentコレクションの新しいインスタンスを返しますが、collapseflattenflipkeyspluckzipメソッドは、基本のコレクションインスタンスを返します。同様に、map操作がEloquentモデルを含まないコレクションを返す場合、それは基本コレクションインスタンスに変換されます。While most Eloquent collection methods return a new instance of an Eloquent collection, the collapse, flatten, flip, keys, pluck, and zip methods return a base collection[/docs/{{version}}/collections] instance. Likewise, if a map operation returns a collection that does not contain any Eloquent models, it will be converted to a base collection instance.

利用可能なメソッドAvailable Methods

すべてのEloquentコレクションはベースのLaravelコレクションオブジェクトを拡張します。したがって、これらは基本コレクションクラスによって提供されるすべての強力なメソッドを継承します。All Eloquent collections extend the base Laravel collection[/docs/{{version}}/collections#available-methods] object; therefore, they inherit all of the powerful methods provided by the base collection class.

さらに、Illuminate\Database\Eloquent\Collectionクラスは、モデルコレクションの管理を支援するメソッドのスーパーセットを提供します。ほとんどのメソッドはIlluminate\Database\Eloquent\Collectionインスタンスを返します。ただし、modelKeysなどの一部のメソッドは、Illuminate\Support\Collectionインスタンスを返します。In addition, the Illuminate\Database\Eloquent\Collection class provides a superset of methods to aid with managing your model collections. Most methods return Illuminate\Database\Eloquent\Collection instances; however, some methods, like modelKeys, return an Illuminate\Support\Collection instance.

contains($key, $operator = null, $value = null) contains($key, $operator = null, $value = null)

containsメソッドを使い、指定モデルインスタンスがコレクションに含まれているかどうかを判定できます。このメソッドは、主キーまたはモデルインスタンスを引数に取ります。The contains method may be used to determine if a given model instance is contained by the collection. This method accepts a primary key or a model instance:

$users->contains(1);

$users->contains(User::find(1));

diff($items) diff($items)

diffメソッドは、指定コレクションに存在しないすべてのモデルを返します。The diff method returns all of the models that are not present in the given collection:

use App\Models\User;

$users = $users->diff(User::whereIn('id', [1, 2, 3])->get());

except($keys) except($keys)

exceptメソッドは、指定する主キーを持たないすべてのモデルを返します。The except method returns all of the models that do not have the given primary keys:

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

find($key) find($key)

findメソッドは、指定キーと一致する主キーを持つモデルを返します。$keyがモデルインスタンスの場合、findは主キーに一致するモデルを返そうとします。$keyがキーの配列である場合、findは指定配列の中の主キーを持つすべてのモデルを返します。The find method returns the model that has a primary key matching the given key. If $key is a model instance, find will attempt to return a model matching the primary key. If $key is an array of keys, find will return all models which have a primary key in the given array:

$users = User::all();

$user = $users->find(1);

fresh($with = []) fresh($with = [])

freshメソッドは、データベースからコレクション内の各モデルの新しいインスタンスを取得します。さらに、指定したリレーションはすべてEagerロードされます。The fresh method retrieves a fresh instance of each model in the collection from the database. In addition, any specified relationships will be eager loaded:

$users = $users->fresh();

$users = $users->fresh('comments');

intersect($items) intersect($items)

intersectメソッドは、指定コレクションにも存在するすべてのモデルを返します。The intersect method returns all of the models that are also present in the given collection:

use App\Models\User;

$users = $users->intersect(User::whereIn('id', [1, 2, 3])->get());

load($relations) load($relations)

loadメソッドは、コレクション内のすべてのモデルに対して指定するリレーションをEagerロードします。The load method eager loads the given relationships for all models in the collection:

$users->load(['comments', 'posts']);

$users->load('comments.author');

loadMissing($relations) loadMissing($relations)

loadMissingメソッドは、関係がまだロードされていない場合、コレクション内のすべてのモデルに対して指定するリレーションをEagerロードします。The loadMissing method eager loads the given relationships for all models in the collection if the relationships are not already loaded:

$users->loadMissing(['comments', 'posts']);

$users->loadMissing('comments.author');

modelKeys() modelKeys()

modelKeysメソッドは、コレクション内のすべてのモデルの主キーを返します。The modelKeys method returns the primary keys for all models in the collection:

$users->modelKeys();

// [1, 2, 3, 4, 5]

makeVisible($attributes) makeVisible($attributes)

makeVisibleメソッドは、通常コレクション内の各モデルで"hidden"になっている属性をvisibleにしますThe makeVisible method makes attributes visible[/docs/{{version}}/eloquent-serialization#hiding-attributes-from-json] that are typically "hidden" on each model in the collection:

$users = $users->makeVisible(['address', 'phone_number']);

makeHidden($attributes) makeHidden($attributes)

makeHiddenメソッドは、通常コレクション内の各モデルで"visible"になっている属性をhiddenにしますThe makeHidden method hides attributes[/docs/{{version}}/eloquent-serialization#hiding-attributes-from-json] that are typically "visible" on each model in the collection:

$users = $users->makeHidden(['address', 'phone_number']);

only($keys) only($keys)

onlyメソッドは、指定主キーを持つすべてのモデルを返します。The only method returns all of the models that have the given primary keys:

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

toQuery() toQuery()

toQueryメソッドは、コレクションモデルの主キーに対するwhereIn制約を含むEloquentクエリビルダインスタンスを返します。The toQuery method returns an Eloquent query builder instance containing a whereIn constraint on the collection model's primary keys:

use App\Models\User;

$users = User::where('status', 'VIP')->get();

$users->toQuery()->update([
    'status' => 'Administrator',
]);

unique($key = null, $strict = false) unique($key = null, $strict = false)

uniqueメソッドは、コレクション内のすべての一意のモデルを返します。コレクション内の、同じタイプで同じ主キーを持つモデルをすべて削除します。The unique method returns all of the unique models in the collection. Any models of the same type with the same primary key as another model in the collection are removed:

$users = $users->unique();

カスタムコレクションCustom Collections

特定のモデルを操作するときにカスタムのCollectionオブジェクトを使用したい場合は、モデルでnewCollectionメソッドを定義します。If you would like to use a custom Collection object when interacting with a given model, you may define a newCollection method on your model:

<?php

namespace App\Models;

use App\Support\UserCollection;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 新しいEloquentCollectionインスタンスの作成
     *
     * @param  array  $models
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function newCollection(array $models = [])
    {
        return new UserCollection($models);
    }
}

newCollectionメソッドを一度定義したら、Eloquentが通常Illuminate\Database\Eloquent\Collectionインスタンスを返すときは、いつでもカスタムコレクションのインスタンスを受け取ります。アプリケーションのすべてのモデルにカスタムコレクションを使用する場合は、アプリケーションのすべてのモデルによって拡張される基本モデルクラスでnewCollectionメソッドを定義する必要があります。Once you have defined a newCollection method, you will receive an instance of your custom collection anytime Eloquent would normally return an Illuminate\Database\Eloquent\Collection instance. If you would like to use a custom collection for every model in your application, you should define the newCollection method on a base model class that is extended by all of your application's models.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作