イントロダクションIntroduction
get
メソッドであれリレーションによるものであれ、Eloquentが複数のレコードをリターンする場合Illuminate\Database\Eloquent\Collection
オブジェクトが返されます。EloquentコレクションオブジェクトはLaravelのベースコレクションを継承しているので、Eloquentモデルの裏にある配列をスムーズに操作するために継承した多くのメソッドがもちろん使用できます。All multi-result sets returned by
Eloquent are instances of the
Illuminate\Database\Eloquent\Collection
object, including results retrieved via the
get
method or accessed via a
relationship. The Eloquent collection object extends
the Laravel base
collection[/docs/{{version}}/collections],
so it naturally inherits dozens of methods used to
fluently work with the underlying array of Eloquent
models.
全コレクションはイテレーターとしても動作し、シンプルなPHP配列のようにループで取り扱うことができます。All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:
$users = App\User::where('active', 1)->get();
foreach ($users as $user) {
echo $user->name;
}
しかし、コレクションは配列よりもパワフルで直感的なインターフェイスを使ったメソッドチェーンにより、マッピングや要素の省略操作を行うことができます。例としてアクティブでないモデルを削除し、残ったユーザーのファーストネームを集めてみましょう。However, 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, let's remove all inactive models and gather the first name for each remaining user:
$users = App\User::all();
$names = $users->reject(function ($user) {
return $user->active === false;
})
->map(function ($user) {
return $user->name;
});
Note:
ほとんどのEloquentコレクションは新しいEloquentコレクションのインスタンスを返しますが、pluck
、keys
、zip
、collapse
、flatten
、flip
メソッドはベースのコレクションインスタンスを返します。Eloquentモデルをまったく含まないコレクションを返すmap
操作のような場合、自動的にベースコレクションへキャストされます。{note} While most Eloquent collection methods return a new instance of an Eloquent collection, thepluck
,keys
,zip
,collapse
,flatten
andflip
methods return a base collection[/docs/{{version}}/collections] instance. Likewise, if amap
operation returns a collection that does not contain any Eloquent models, it will be automatically cast to a base collection.
使用できるメソッド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
インスタンスを返しますが、いくつかのメソッドは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 return a base
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\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)
{#collection-method
.first-collection-method}find($key)
{#collection-method
.first-collection-method}
find
メソッドは、指定した主キーのモデルを見つけます。$key
がモデルインスタンスの場合、find
はその主キーと一致するモデルを返そうとします。$key
がキーの配列の場合はwhereIn()
を使用して、$key
と一致するモデルをすべて返します。The find
method
finds a model that has a given primary 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 match the $keys
using
whereIn()
:
$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\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 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 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]);
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
自分で拡張したメソッドを含むカスタム「コレクション」オブジェクトを使いたい場合は、モデルのnewCollection
メソッドをオーバーライドしてください。If you need to use a custom
Collection
object with your own
extension methods, you may override the
newCollection
method on your
model:
<?php
namespace App;
use App\CustomCollection;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* 新しいEloqunetコレクションインスタンスの生成
*
* @param array $models
* @return \Illuminate\Database\Eloquent\Collection
*/
public function newCollection(array $models = [])
{
return new CustomCollection($models);
}
}
newCollection
メソッドを定義すれば、Eloquentがそのモデルの「コレクション」インスタンスを返す場合にいつでもカスタムコレクションのインスタンスを受け取れます。アプリケーションの全モデルでカスタムコレクションを使いたい場合は、全モデルが拡張しているモデルのベースクラスでnewCollection
メソッドをオーバーライドしてください。Once you have defined a
newCollection
method, you will receive
an instance of your custom collection anytime
Eloquent returns a Collection
instance
of that model. If you would like to use a custom
collection for every model in your application, you
should override the newCollection
method on a base model class that is extended by all
of your models.