aggregate
1. Introduction
All result sets containing multiple records returned by Eloquent are Illuminate\Database\Eloquent\Collection
Instances of objects, including through get
Method or the result obtained by accessing the association relationship. The Eloquent collection object inherits from the collection base class of Laravel, so it naturally inherits many methods for processing the underlying array of the Eloquent model.
Of course, all collections are also iterators, allowing you to loop them like arrays:
$users = App\User::where('active', 1)->get(); foreach ($users as $user) { echo $user->name; }
However, collections are more powerful than arrays because they provide various mapping/simplification operations using intuitive interfaces. For example, we can remove all invalid models and aggregate the names of existing users in the following ways:
$users = App\User::where('active', 1)->get(); $names = $users->reject(function ($user) { return $user->active === false; })->map(function ($user) { return $user->name; });
Note: Although most Eloquent collections return a new Eloquent collection instance pluck
、 keys
、 zip
、 collapse
、 flatten
and flip
Method returns a collection base class instance.
2. Available methods
All Eloquent collections inherit from the base class of the Laravel collection object. Therefore, they inherit the Powerful approach 。
3. Custom Collection
If you need to use custom collection objects in your own extended methods, you can override the newCollection
method:
<? php namespace App; use App\CustomCollection; use Illuminate\Database\Eloquent\Model; class User extends Model{ /** *Create a new Eloquent collection instance * * @param array $models * @return \Illuminate\Database\Eloquent\Collection */ public function newCollection(array $models = []) { return new CustomCollection($models); } }
Well defined newCollection
Method, Eloquent returns the Collection
You will get custom collections for all instances. If you want to use custom collections in each model in the application, you need to override them in the model base class newCollection
method.