Class ResultSet
Represents the results obtained after executing a query for a specific table This object is responsible for correctly nesting result keys reported from the query, casting each field to the correct type and executing the extra queries required for eager loading external associations.
Property Summary
- 
        $_autoFields protected
boolTracks value of $_autoFields property of $query passed to constructor.
 - 
        $_containMap protected
arrayList of associations that should be eager loaded.
 - 
        $_count protected
intHolds the count of records in this result set
 - 
        $_current protected
arrayLast record fetched from the statement
 - 
        $_defaultAlias protected
stringThe default table alias
 - 
        $_defaultTable protected
Cake\ORM\Table|Cake\Datasource\RepositoryInterfaceDefault table instance
 - 
        $_driver protected
Cake\Database\DriverThe Database driver object.
 - 
        $_entityClass protected
stringThe fully namespaced name of the class to use for hydrating results
 - 
        $_hydrate protected
boolWhether to hydrate results into objects or not
 - 
        $_index protected
intPoints to the next record number that should be fetched
 - 
        $_map protected
arrayMap of fields that are fetched from the statement with their type and the table they belong to
 - 
        $_matchingMap protected
arrayList of associations that should be placed under the
_matchingDataresult key. - 
        $_matchingMapColumns protected
arrayList of matching associations and the column keys to expect from each of them.
 - 
        $_query protected deprecated
Cake\ORM\QueryOriginal query from where results were generated
 - 
        $_results protected
array|ArrayAccessResults that have been fetched or hydrated into the results.
 - 
        $_statement protected
Cake\Database\StatementInterfaceDatabase statement holding the results
 - 
        $_types protected
arrayType cache for type converters.
 - 
        $_useBuffering protected
boolWhether or not to buffer results fetched from the statement
 
Method Summary
- 
          
__construct() public
Constructor
 - 
          
__debugInfo() public
Returns an array that can be used to describe the internal state of this object.
 - 
          
_calculateAssociationMap() protected
Calculates the list of associations that should get eager loaded when fetching each record
 - 
          
_calculateColumnMap() protected
Creates a map of row keys out of the query select clause that can be used to hydrate nested result sets more quickly.
 - 
          
_calculateTypeMap() protected deprecated
Creates a map of Type converter classes for each of the columns that should be fetched by this object.
 - 
          
_castValues() protected deprecated
Casts all values from a row brought from a table to the correct PHP type.
 - 
          
_createMatcherFilter() protected
Returns a callable that receives a value and will return whether or not it matches certain condition.
 - 
          
_extract() protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with
{*} - 
          
_fetchResult() protected
Helper function to fetch the next result from the statement or seeded results.
 - 
          
_getTypes() protected
Returns the Type classes for each of the passed fields belonging to the table.
 - 
          
_groupResult() protected
Correctly nests results keys including those coming from associations
 - 
          
_propertyExtractor() protected
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
 - 
          
_simpleExtract() protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path
 - 
          
_unwrap() public deprecated
Backwards compatible wrapper for unwrap()
 - 
          
append() public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
 - 
          
appendItem() public
{@inheritDoc}
 - 
          
avg() public
Returns the average of all the values extracted with $matcher or of this collection.
 - 
          
buffered() public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
 - 
          
cartesianProduct() public
{@inheritDoc}
 - 
          
chunk() public
Breaks the collection into smaller arrays of the given size.
 - 
          
chunkWithKeys() public
Breaks the collection into smaller arrays of the given size.
 - 
          
combine() public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
 - 
          
compile() public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
 - 
          
contains() public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
 - 
          
count() public
Gives the number of rows in the result set.
 - 
          
countBy() public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
 - 
          
countKeys() public
Returns the number of unique keys in this iterator. This is, the number of elements the collection will contain after calling
toArray() - 
          
current() public
Returns the current record in the result iterator
 - 
          
each() public
Executes the passed callable for each of the elements in this collection and passes both the value and key for them on each step. Returns the same collection for chaining.
 - 
          
every() public
Returns true if all values in this collection pass the truth test provided in the callback.
 - 
          
extract() public
Returns a new collection containing the column or property value found in each of the elements, as requested in the $matcher param.
 - 
          
filter() public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
 - 
          
first() public
Get the first record from a result set.
 - 
          
firstMatch() public
Returns the first result matching all of the key-value pairs listed in conditions.
 - 
          
groupBy() public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
 - 
          
indexBy() public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
 - 
          
insert() public
Returns a new collection containing each of the elements found in
$valuesas a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the$pathparameter. - 
          
isEmpty() public
Returns whether or not there are elements in this collection
 - 
          
jsonSerialize() public
Convert a result set into JSON.
 - 
          
key() public
Returns the key of the current record in the iterator
 - 
          
last() public
Returns the last result in this collection
 - 
          
listNested() public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
 - 
          
map() public
Returns another collection after modifying each of the values in this one using the provided callable.
 - 
          
match() public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
 - 
          
max() public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $type parameters
 - 
          
median() public
Returns the median of all the values extracted with $matcher or of this collection.
 - 
          
min() public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $type parameters
 - 
          
nest() public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
 - 
          
next() public
Advances the iterator pointer to the next record
 - 
          
optimizeUnwrap() protected
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
 - 
          
prepend() public
{@inheritDoc}
 - 
          
prependItem() public
{@inheritDoc}
 - 
          
reduce() public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
 - 
          
reject() public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of
filter. - 
          
rewind() public
Rewinds a ResultSet.
 - 
          
sample() public
Returns a new collection with maximum $size random elements from this collection
 - 
          
serialize() public
Serializes a resultset.
 - 
          
shuffle() public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
 - 
          
skip() public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
 - 
          
some() public
Returns true if any of the values in this collection pass the truth test provided in the callback.
 - 
          
sortBy() public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
 - 
          
stopWhen() public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to false.
 - 
          
sumOf() public
Returns the total sum of all the values extracted with $matcher or of this collection.
 - 
          
take() public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
 - 
          
through() public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
 - 
          
toArray() public
Returns an array representation of the results
 - 
          
toList() public
Returns an numerically-indexed array representation of the results. This is equivalent to calling
toArray(false) - 
          
transpose() public
Transpose rows and columns into columns and rows
 - 
          
unfold() public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
 - 
          
unserialize() public
Unserializes a resultset.
 - 
          
unwrap() public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
 - 
          
valid() public
Whether there are more results to be fetched from the iterator
 - 
          
zip() public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
 - 
          
zipWith() public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
 
Method Detail
__construct() ¶ public
__construct(Cake\ORM\Query $query, Cake\Database\StatementInterface $statement)
      Constructor
Parameters
- 
                
Cake\ORM\Query$query Query from where results come
- 
                
Cake\Database\StatementInterface$statement The statement to fetch from
__debugInfo() ¶ public
__debugInfo(): array
      Returns an array that can be used to describe the internal state of this object.
Returns
array_calculateAssociationMap() ¶ protected
_calculateAssociationMap(Cake\ORM\Query $query): void
      Calculates the list of associations that should get eager loaded when fetching each record
Parameters
- 
                
Cake\ORM\Query$query The query from where to derive the associations
Returns
void_calculateColumnMap() ¶ protected
_calculateColumnMap(Cake\ORM\Query $query): void
      Creates a map of row keys out of the query select clause that can be used to hydrate nested result sets more quickly.
Parameters
- 
                
Cake\ORM\Query$query The query from where to derive the column map
Returns
void_calculateTypeMap() ¶ protected
_calculateTypeMap(): void
      Creates a map of Type converter classes for each of the columns that should be fetched by this object.
Returns
void_castValues() ¶ protected
_castValues(string $alias, array $values): array
      Casts all values from a row brought from a table to the correct PHP type.
Parameters
- 
                
string$alias The table object alias
- 
                
array$values The values to cast
Returns
array_createMatcherFilter() ¶ protected
_createMatcherFilter(array $conditions): callable
      Returns a callable that receives a value and will return whether or not it matches certain condition.
Parameters
- 
                
array$conditions A key-value list of conditions to match where the key is the property path to get from the current item and the value is the value to be compared the item with.
Returns
callable_extract() ¶ protected
_extract(array|ArrayAccess $data, array $path): mixed
      Returns a column from $data that can be extracted
by iterating over the column names contained in $path.
It will return arrays for elements in represented with {*}
Parameters
- 
                
array|ArrayAccess$data Data.
- 
                
array$path Path to extract from.
Returns
mixed_fetchResult() ¶ protected
_fetchResult(): mixed
      Helper function to fetch the next result from the statement or seeded results.
Returns
mixed_getTypes() ¶ protected
_getTypes(Cake\ORM\Table $table, array $fields): array
      Returns the Type classes for each of the passed fields belonging to the table.
Parameters
- 
                
Cake\ORM\Table$table The table from which to get the schema
- 
                
array$fields The fields whitelist to use for fields in the schema.
Returns
array_groupResult() ¶ protected
_groupResult(array $row): array
      Correctly nests results keys including those coming from associations
Parameters
- 
                
array$row Array containing columns and values or false if there is no results
Returns
arrayResults
_propertyExtractor() ¶ protected
_propertyExtractor(string|callable $callback): callable
      Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
Parameters
- 
                
string|callable$callback A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
Returns
callable_simpleExtract() ¶ protected
_simpleExtract(array|ArrayAccess $data, array $path): mixed
      Returns a column from $data that can be extracted by iterating over the column names contained in $path
Parameters
- 
                
array|ArrayAccess$data Data.
- 
                
array$path Path to extract from.
Returns
mixed_unwrap() ¶ public
_unwrap(): Traversable
      Backwards compatible wrapper for unwrap()
Returns
Traversableappend() ¶ public
append(array|Traversable $items): Cake\Collection\CollectionInterface
      Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
Parameters
- 
                
array|Traversable$items 
Returns
Cake\Collection\CollectionInterfaceappendItem() ¶ public
appendItem(mixed $item, mixed $key = null)
      {@inheritDoc}
Parameters
- 
                
$item - 
                
$key optional 
avg() ¶ public
avg(string|callable|null $matcher = null): float|int|null
      Returns the average of all the values extracted with $matcher or of this collection.
Example:
$items = [
 ['invoice' => ['total' => 100]],
 ['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
        
                  Parameters
- 
                
string|callable|null$matcher optional 
Returns
float|int|nullbuffered() ¶ public
buffered(): Cake\Collection\Iterator\BufferedIterator
      Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
Returns
Cake\Collection\Iterator\BufferedIteratorcartesianProduct() ¶ public
cartesianProduct(callable $operation = null, callable $filter = null): Cake\Collection\CollectionInterface
      {@inheritDoc}
Parameters
- 
                
callable$operation optional - 
                
callable$filter optional 
Returns
Cake\Collection\CollectionInterfacechunk() ¶ public
chunk(int $chunkSize): Cake\Collection\CollectionInterface
      Breaks the collection into smaller arrays of the given size.
Example:
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
        
                  Parameters
- 
                
int$chunkSize 
Returns
Cake\Collection\CollectionInterfacechunkWithKeys() ¶ public
chunkWithKeys(int $chunkSize, bool $preserveKeys = true): Cake\Collection\CollectionInterface
      Breaks the collection into smaller arrays of the given size.
Example:
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
        
                  Parameters
- 
                
int$chunkSize - 
                
bool$preserveKeys optional 
Returns
Cake\Collection\CollectionInterfacecombine() ¶ public
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): Cake\Collection\CollectionInterface
      Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
Examples:
$items = [
 ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
 ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
 ['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
 1 => 'foo',
 2 => 'bar',
 3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
 'a' => [1 => 'foo', 3 => 'baz'],
 'b' => [2 => 'bar']
];
        
                  Parameters
- 
                
callable|string$keyPath - 
                
callable|string$valuePath - 
                
callable|string|null$groupPath optional 
Returns
Cake\Collection\CollectionInterfacecompile() ¶ public
compile(bool $preserveKeys = true): Cake\Collection\CollectionInterface
      Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
Example:
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
In the above example, had the collection not been compiled before, the
iterations for map, sortBy and extract would've been executed twice:
once for getting $isJohnHere and once for $allButJohn
You can think of this method as a way to create save points for complex calculations in a collection.
Parameters
- 
                
bool$preserveKeys optional 
Returns
Cake\Collection\CollectionInterfacecontains() ¶ public
contains(mixed $value): bool
      Returns true if $value is present in this collection. Comparisons are made both by value and type.
Parameters
- 
                
mixed$value 
Returns
boolcount() ¶ public
count(): int
      Gives the number of rows in the result set.
Part of the Countable interface.
Returns
intcountBy() ¶ public
countBy(callable|string $callback): Cake\Collection\CollectionInterface
      Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
Example:
$items = [
 ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
 ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
 ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
 return $e['parent_id'];
});
// Result will look like this when converted to array
[
 10 => 2,
 11 => 1
];
        
                  Parameters
- 
                
callable|string$callback 
Returns
Cake\Collection\CollectionInterfacecountKeys() ¶ public
countKeys(): int
      Returns the number of unique keys in this iterator. This is, the number of
elements the collection will contain after calling toArray()
This method comes with a number of caveats. Please refer to CollectionInterface::count()
for details.
Returns
intcurrent() ¶ public
current(): array|object
      Returns the current record in the result iterator
Part of Iterator interface.
Returns
array|objecteach() ¶ public
each(callable $c): Cake\Collection\CollectionInterface
      Executes the passed callable for each of the elements in this collection and passes both the value and key for them on each step. Returns the same collection for chaining.
Example:
$collection = (new Collection($items))->each(function ($value, $key) {
 echo "Element $key: $value";
});
        
                  Parameters
- 
                
callable$c 
Returns
Cake\Collection\CollectionInterfaceevery() ¶ public
every(callable $c): bool
      Returns true if all values in this collection pass the truth test provided in the callback.
Each time the callback is executed it will receive the value of the element in the current iteration and the key of the element as arguments, in that order.
Example:
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
 return $value > 21;
});
Empty collections always return true because it is a vacuous truth.
Parameters
- 
                
callable$c 
Returns
boolextract() ¶ public
extract(string $matcher): Cake\Collection\CollectionInterface
      Returns a new collection containing the column or property value found in each of the elements, as requested in the $matcher param.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
Example:
Extract the user name for all comments in the array:
$items = [
 ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
 ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
It is also possible to extract a flattened collection out of nested properties
 $items = [
     ['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
     ['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
        
                  Parameters
- 
                
string$matcher 
Returns
Cake\Collection\CollectionInterfacefilter() ¶ public
filter(callable|null $c = null): Cake\Collection\Iterator\FilterIterator
      Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
 return $value % 2 === 0;
});
        
                  Parameters
- 
                
callable|null$c optional 
Returns
Cake\Collection\Iterator\FilterIteratorfirst() ¶ public
first(): array|object
      Get the first record from a result set.
This method will also close the underlying statement cursor.
Returns
array|objectfirstMatch() ¶ public
firstMatch(array $conditions): mixed
      Returns the first result matching all of the key-value pairs listed in conditions.
Parameters
- 
                
array$conditions 
Returns
mixedgroupBy() ¶ public
groupBy(callable|string $callback): Cake\Collection\CollectionInterface
      Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
Example:
$items = [
 ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
 ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
 ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
 return $e['parent_id'];
});
// Result will look like this when converted to array
[
 10 => [
     ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
     ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
 ],
 11 => [
     ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
 ]
];
        
                  Parameters
- 
                
callable|string$callback 
Returns
Cake\Collection\CollectionInterfaceindexBy() ¶ public
indexBy(callable|string $callback): Cake\Collection\CollectionInterface
      Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
Example:
$items = [
 ['id' => 1, 'name' => 'foo'],
 ['id' => 2, 'name' => 'bar'],
 ['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
 return $e['id'];
});
// Result will look like this when converted to array
[
 1 => ['id' => 1, 'name' => 'foo'],
 3 => ['id' => 3, 'name' => 'baz'],
 2 => ['id' => 2, 'name' => 'bar'],
];
        
                  Parameters
- 
                
callable|string$callback 
Returns
Cake\Collection\CollectionInterfaceinsert() ¶ public
insert(string $path, mixed $values): Cake\Collection\Iterator\InsertIterator
      Returns a new collection containing each of the elements found in $values as
a property inside the corresponding elements in this collection. The property
where the values will be inserted is described by the $path parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
Example:
Insert ages into a collection containing users:
$items = [
 ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
 ['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
 ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
 ['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
        
                  Parameters
- 
                
string$path - 
                
mixed$values 
Returns
Cake\Collection\Iterator\InsertIteratorisEmpty() ¶ public
isEmpty(): bool
      Returns whether or not there are elements in this collection
Example:
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
(new Collection([]))->isEmpty(); // true
        
        
                  Returns
booljsonSerialize() ¶ public
jsonSerialize(): array
      Convert a result set into JSON.
Part of JsonSerializable interface.
Returns
arraykey() ¶ public
key(): int
      Returns the key of the current record in the iterator
Part of Iterator interface.
Returns
intlistNested() ¶ public
listNested(string|int $dir = 'desc', string|callable $nestingKey = 'children'): Cake\Collection\Iterator\TreeIterator
      Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
- desc: TreeIterator::SELF_FIRST
 - asc: TreeIterator::CHILD_FIRST
 - leaves: TreeIterator::LEAVES_ONLY
 
Example:
$collection = new Collection([
 ['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
 ['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
        
                  Parameters
- 
                
string|int$dir optional - 
                
string|callable$nestingKey optional 
Returns
Cake\Collection\Iterator\TreeIteratormap() ¶ public
map(callable $c): Cake\Collection\Iterator\ReplaceIterator
      Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
Example:
Getting a collection of booleans where true indicates if a person is female:
$collection = (new Collection($people))->map(function ($person, $key) {
 return $person->gender === 'female';
});
        
                  Parameters
- 
                
callable$c 
Returns
Cake\Collection\Iterator\ReplaceIteratormatch() ¶ public
match(array $conditions): Cake\Collection\CollectionInterface
      Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
Example:
$items = [
 ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
 ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
 ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
        
                  Parameters
- 
                
array$conditions 
Returns
Cake\Collection\CollectionInterfacemax() ¶ public
max(callable|string $callback, int $type = \SORT_NUMERIC): mixed
      Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $type parameters
Examples:
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
 return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
        
                  Parameters
- 
                
callable|string$callback - 
                
int$type optional 
Returns
mixedmedian() ¶ public
median(string|callable|null $matcher = null): float|int|null
      Returns the median of all the values extracted with $matcher or of this collection.
Example:
$items = [
 ['invoice' => ['total' => 400]],
 ['invoice' => ['total' => 500]]
 ['invoice' => ['total' => 100]]
 ['invoice' => ['total' => 333]]
 ['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
        
                  Parameters
- 
                
string|callable|null$matcher optional 
Returns
float|int|nullmin() ¶ public
min(callable|string $callback, int $type = \SORT_NUMERIC): mixed
      Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $type parameters
Examples:
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
 return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
        
                  Parameters
- 
                
callable|string$callback - 
                
int$type optional 
Returns
mixednest() ¶ public
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): Cake\Collection\CollectionInterface
      Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
Parameters
- 
                
callable|string$idPath - 
                
callable|string$parentPath - 
                
string$nestingKey optional 
Returns
Cake\Collection\CollectionInterfacenext() ¶ public
next(): void
      Advances the iterator pointer to the next record
Part of Iterator interface.
Returns
voidoptimizeUnwrap() ¶ protected
optimizeUnwrap(): Traversable|array
      Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
Returns
Traversable|arrayprependItem() ¶ public
prependItem(mixed $item, mixed $key = null)
      {@inheritDoc}
Parameters
- 
                
$item - 
                
$key optional 
reduce() ¶ public
reduce(callable $c, mixed $zero = null): mixed
      Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
Parameters
- 
                
callable$c - 
                
mixed$zero optional 
Returns
mixedreject() ¶ public
reject(callable $c): Cake\Collection\Iterator\FilterIterator
      Looks through each value in the collection, and returns another collection with
all the values that do not pass a truth test. This is the opposite of filter.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
 return $value % 2 === 0;
});
        
                  Parameters
- 
                
callable$c 
Returns
Cake\Collection\Iterator\FilterIteratorrewind() ¶ public
rewind(): void
      Rewinds a ResultSet.
Part of Iterator interface.
Returns
voidThrows
Cake\Database\Exceptionsample() ¶ public
sample(int $size = 10): Cake\Collection\CollectionInterface
      Returns a new collection with maximum $size random elements from this collection
Parameters
- 
                
int$size optional 
Returns
Cake\Collection\CollectionInterfaceserialize() ¶ public
serialize(): string
      Serializes a resultset.
Part of Serializable interface.
Returns
stringSerialized object
shuffle() ¶ public
shuffle(): Cake\Collection\CollectionInterface
      Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
Returns
Cake\Collection\CollectionInterfaceskip() ¶ public
skip(int $howMany): Cake\Collection\CollectionInterface
      Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
Parameters
- 
                
int$howMany 
Returns
Cake\Collection\CollectionInterfacesome() ¶ public
some(callable $c): bool
      Returns true if any of the values in this collection pass the truth test provided in the callback.
Each time the callback is executed it will receive the value of the element in the current iteration and the key of the element as arguments, in that order.
Example:
$hasYoungPeople = (new Collection([24, 45, 15]))->every(function ($value, $key) {
 return $value < 21;
});
        
                  Parameters
- 
                
callable$c 
Returns
boolsortBy() ¶ public
sortBy(callable|string $callback, int $dir = \SORT_DESC, int $type = \SORT_NUMERIC): Cake\Collection\CollectionInterface
      Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
Example:
$items = $collection->sortBy(function ($user) {
 return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
 echo $user->name;
}
        
                  Parameters
- 
                
callable|string$callback - 
                
int$dir optional - 
                
int$type optional 
Returns
Cake\Collection\CollectionInterfacestopWhen() ¶ public
stopWhen(callable $condition): Cake\Collection\Iterator\StoppableIterator
      Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to false.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
 return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
Get elements until the first unapproved message is found:
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
        
                  Parameters
- 
                
callable$condition 
Returns
Cake\Collection\Iterator\StoppableIteratorsumOf() ¶ public
sumOf(string|callable|null $matcher = null): float|int
      Returns the total sum of all the values extracted with $matcher or of this collection.
Example:
$items = [
 ['invoice' => ['total' => 100]],
 ['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
        
                  Parameters
- 
                
string|callable|null$matcher optional 
Returns
float|inttake() ¶ public
take(int $size = 1, int $from = 0): Cake\Collection\CollectionInterface
      Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
Parameters
- 
                
int$size optional - 
                
int$from optional 
Returns
Cake\Collection\CollectionInterfacethrough() ¶ public
through(callable $handler): Cake\Collection\CollectionInterface
      Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
Example:
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
     return new MyCustomCollection($collection);
});
        
                  Parameters
- 
                
callable$handler 
Returns
Cake\Collection\CollectionInterfacetoArray() ¶ public
toArray(bool $preserveKeys = true): array
      Returns an array representation of the results
Parameters
- 
                
bool$preserveKeys optional 
Returns
arraytoList() ¶ public
toList(): array
      Returns an numerically-indexed array representation of the results.
This is equivalent to calling toArray(false)
Returns
arraytranspose() ¶ public
transpose(): Cake\Collection\CollectionInterface
      Transpose rows and columns into columns and rows
Example:
$items = [
      ['Products', '2012', '2013', '2014'],
      ['Product A', '200', '100', '50'],
      ['Product B', '300', '200', '100'],
      ['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
//     ['Products', 'Product A', 'Product B', 'Product C'],
//     ['2012', '200', '300', '400'],
//     ['2013', '100', '200', '300'],
//     ['2014', '50', '100', '200'],
// ]
        
        
                  Returns
Cake\Collection\CollectionInterfaceunfold() ¶ public
unfold(callable|null $transformer = null): Cake\Collection\CollectionInterface
      Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
Example:
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
Using a transformer
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
 return $service->fetchPage($page)->toArray();
});
        
                  Parameters
- 
                
callable|null$transformer optional 
Returns
Cake\Collection\CollectionInterfaceunserialize() ¶ public
unserialize(string $serialized): void
      Unserializes a resultset.
Part of Serializable interface.
Parameters
- 
                
string$serialized Serialized object
Returns
voidunwrap() ¶ public
unwrap(): Traversable
      Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
Returns
Traversablevalid() ¶ public
valid(): bool
      Whether there are more results to be fetched from the iterator
Part of Iterator interface.
Returns
boolzip() ¶ public
zip(array|Traversable $items): Cake\Collection\CollectionInterface
      Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Example:
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
        
                  Parameters
- 
                
array|Traversable$items 
Returns
Cake\Collection\CollectionInterfacezipWith() ¶ public
zipWith(array|Traversable $items, callable $callable): Cake\Collection\CollectionInterface
      Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
Example:
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
  return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
        
                  Parameters
- 
                
array|Traversable$items - 
                
callable$callable 
Returns
Cake\Collection\CollectionInterfaceProperty Detail
$_autoFields ¶ protected
Tracks value of $_autoFields property of $query passed to constructor.
Type
bool$_defaultTable ¶ protected
Default table instance
Type
Cake\ORM\Table|Cake\Datasource\RepositoryInterface$_driver ¶ protected
The Database driver object.
Cached in a property to avoid multiple calls to the same function.
Type
Cake\Database\Driver$_entityClass ¶ protected
The fully namespaced name of the class to use for hydrating results
Type
string$_map ¶ protected
Map of fields that are fetched from the statement with their type and the table they belong to
Type
array$_matchingMap ¶ protected
List of associations that should be placed under the _matchingData
result key.
Type
array$_matchingMapColumns ¶ protected
List of matching associations and the column keys to expect from each of them.
Type
array$_results ¶ protected
Results that have been fetched or hydrated into the results.
Type
array|ArrayAccess$_statement ¶ protected
Database statement holding the results
Type
Cake\Database\StatementInterface$_types ¶ protected
Type cache for type converters.
Converters are indexed by alias and column name.
Type
array