QueryTrait
Contains the characteristics for an object that is attached to a repository and can retrieve results based on any criteria.
Table of Contents
Properties
- $_cache : QueryCacher|null
- A query cacher instance if this query has caching enabled.
- $_eagerLoaded : bool
- Whether the query is standalone or the product of an eager load operation.
- $_formatters : array<string|int, callable>
- List of formatter classes or callbacks that will post-process the results when fetched
- $_mapReduce : array<string|int, mixed>
- List of map-reduce routines that should be applied over the query result
- $_options : array<string|int, mixed>
- Holds any custom options passed using applyOptions that could not be processed by any method in this class.
- $_repository : RepositoryInterface
- Instance of a table object this query is bound to
- $_results : iterable<string|int, mixed>|null
- A ResultSet.
Methods
- __call() : mixed
- Enables calling methods from the result set as if they were from this class
- aliasField() : array<string, string>
- Returns a key => value array representing a single aliased field that can be passed directly to the select() method.
- aliasFields() : array<string, string>
- Runs `aliasField()` for each field in the provided list and returns the result under a single array.
- all() : ResultSetInterface
- Fetch the results for this query.
- applyOptions() : $this
- Populates or adds parts to current query clauses using an array.
- cache() : $this
- Enable result caching for this query.
- eagerLoaded() : $this
- Sets the query instance to be an eager loaded query. If no argument is passed, the current configured query `_eagerLoaded` value is returned.
- first() : EntityInterface|array<string|int, mixed>|null
- Returns the first result out of executing this query, if the query has not been executed before, it will set the limit clause to 1 for performance reasons.
- firstOrFail() : EntityInterface|array<string|int, mixed>
- Get the first result from the executing query or raise an exception.
- formatResults() : $this
- Registers a new formatter callback function that is to be executed when trying to fetch the results from the database.
- getIterator() : ResultSetInterface
- Executes this query and returns a results iterator. This function is required for implementing the IteratorAggregate interface and allows the query to be iterated without having to call execute() manually, thus making it look like a result set instead of the query itself.
- getMapReducers() : array<string|int, mixed>
- Returns the list of previously registered map reduce routines.
- getOptions() : array<string|int, mixed>
- Returns an array with the custom options that were applied to this query and that were not already processed by another method in this class.
- getRepository() : RepositoryInterface
- Returns the default table object that will be used by this query, that is, the table that will appear in the from clause.
- getResultFormatters() : array<string|int, callable>
- Returns the list of previously registered format routines.
- isEagerLoaded() : bool
- Returns the current configured query `_eagerLoaded` value
- mapReduce() : $this
- Register a new MapReduce routine to be executed on top of the database results Both the mapper and caller callable should be invokable objects.
- repository() : $this
- Set the default Table object that will be used by this query and form the `FROM` clause.
- setResult() : $this
- Set the result set for a query.
- toArray() : array<string|int, mixed>
- Returns an array representation of the results after executing the query.
- _decorateResults() : ResultSetInterface
- Decorates the results iterator with MapReduce routines and formatters
- _decoratorClass() : string
- Returns the name of the class to be used for decorating results
- _execute() : ResultSetInterface
- Executes this query and returns a traversable object containing the results
Properties
$_cache
A query cacher instance if this query has caching enabled.
protected
QueryCacher|null
$_cache
$_eagerLoaded
Whether the query is standalone or the product of an eager load operation.
protected
bool
$_eagerLoaded
= false
$_formatters
List of formatter classes or callbacks that will post-process the results when fetched
protected
array<string|int, callable>
$_formatters
= []
$_mapReduce
List of map-reduce routines that should be applied over the query result
protected
array<string|int, mixed>
$_mapReduce
= []
$_options
Holds any custom options passed using applyOptions that could not be processed by any method in this class.
protected
array<string|int, mixed>
$_options
= []
$_repository
Instance of a table object this query is bound to
protected
RepositoryInterface
$_repository
$_results
A ResultSet.
protected
iterable<string|int, mixed>|null
$_results
When set, query execution will be bypassed.
Tags
Methods
__call()
Enables calling methods from the result set as if they were from this class
public
__call(string $method, array<string|int, mixed> $arguments) : mixed
Parameters
- $method : string
-
the method to call
- $arguments : array<string|int, mixed>
-
list of arguments for the method to call
Tags
aliasField()
Returns a key => value array representing a single aliased field that can be passed directly to the select() method.
public
aliasField(string $field[, string|null $alias = null ]) : array<string, string>
The key will contain the alias and the value the actual field name.
If the field is already aliased, then it will not be changed. If no $alias is passed, the default table for this query will be used.
Parameters
- $field : string
-
The field to alias
- $alias : string|null = null
-
the alias used to prefix the field
Return values
array<string, string>aliasFields()
Runs `aliasField()` for each field in the provided list and returns the result under a single array.
public
aliasFields(array<string|int, mixed> $fields[, string|null $defaultAlias = null ]) : array<string, string>
Parameters
- $fields : array<string|int, mixed>
-
The fields to alias
- $defaultAlias : string|null = null
-
The default alias
Return values
array<string, string>all()
Fetch the results for this query.
public
all() : ResultSetInterface
Will return either the results set through setResult(), or execute this query and return the ResultSetDecorator object ready for streaming of results.
ResultSetDecorator is a traversable object that implements the methods found on Cake\Collection\Collection.
Return values
ResultSetInterfaceapplyOptions()
Populates or adds parts to current query clauses using an array.
public
abstract applyOptions(array<string, mixed> $options) : $this
This is handy for passing all query clauses at once.
Parameters
- $options : array<string, mixed>
-
the options to be applied
Return values
$thiscache()
Enable result caching for this query.
public
cache(Closure|string|false $key[, CacheInterface|string $config = 'default' ]) : $this
If a query has caching enabled, it will do the following when executed:
- Check the cache for $key. If there are results no SQL will be executed. Instead the cached results will be returned.
- When the cached data is stale/missing the result set will be cached as the query is executed.
Usage
// Simple string key + config
$query->cache('my_key', 'db_results');
// Function to generate key.
$query->cache(function ($q) {
$key = serialize($q->clause('select'));
$key .= serialize($q->clause('where'));
return md5($key);
});
// Using a pre-built cache engine.
$query->cache('my_key', $engine);
// Disable caching
$query->cache(false);
Parameters
- $key : Closure|string|false
-
Either the cache key or a function to generate the cache key. When using a function, this query instance will be supplied as an argument.
- $config : CacheInterface|string = 'default'
-
Either the name of the cache config to use, or a cache engine instance.
Return values
$thiseagerLoaded()
Sets the query instance to be an eager loaded query. If no argument is passed, the current configured query `_eagerLoaded` value is returned.
public
eagerLoaded(bool $value) : $this
Parameters
- $value : bool
-
Whether to eager load.
Return values
$thisfirst()
Returns the first result out of executing this query, if the query has not been executed before, it will set the limit clause to 1 for performance reasons.
public
first() : EntityInterface|array<string|int, mixed>|null
Example:
$singleUser = $query->select(['id', 'username'])->first();
Return values
EntityInterface|array<string|int, mixed>|null —The first result from the ResultSet.
firstOrFail()
Get the first result from the executing query or raise an exception.
public
firstOrFail() : EntityInterface|array<string|int, mixed>
Tags
Return values
EntityInterface|array<string|int, mixed> —The first result from the ResultSet.
formatResults()
Registers a new formatter callback function that is to be executed when trying to fetch the results from the database.
public
formatResults([callable|null $formatter = null ][, int|bool $mode = self::APPEND ]) : $this
If the second argument is set to true, it will erase previous formatters and replace them with the passed first argument.
Callbacks are required to return an iterator object, which will be used as
the return value for this query's result. Formatter functions are applied
after all the MapReduce
routines for this query have been executed.
Formatting callbacks will receive two arguments, the first one being an object
implementing \Cake\Collection\CollectionInterface
, that can be traversed and
modified at will. The second one being the query instance on which the formatter
callback is being applied.
Usually the query instance received by the formatter callback is the same query instance on which the callback was attached to, except for in a joined association, in that case the callback will be invoked on the association source side query, and it will receive that query instance instead of the one on which the callback was originally attached to - see the examples below!
Examples:
Return all results from the table indexed by id:
$query->select(['id', 'name'])->formatResults(function ($results) {
return $results->indexBy('id');
});
Add a new column to the ResultSet:
$query->select(['name', 'birth_date'])->formatResults(function ($results) {
return $results->map(function ($row) {
$row['age'] = $row['birth_date']->diff(new DateTime)->y;
return $row;
});
});
Add a new column to the results with respect to the query's hydration configuration:
$query->formatResults(function ($results, $query) {
return $results->map(function ($row) use ($query) {
$data = [
'bar' => 'baz',
];
if ($query->isHydrationEnabled()) {
$row['foo'] = new Foo($data)
} else {
$row['foo'] = $data;
}
return $row;
});
});
Retaining access to the association target query instance of joined associations, by inheriting the contain callback's query argument:
// Assuming a `Articles belongsTo Authors` association that uses the join strategy
$articlesQuery->contain('Authors', function ($authorsQuery) {
return $authorsQuery->formatResults(function ($results, $query) use ($authorsQuery) {
// Here `$authorsQuery` will always be the instance
// where the callback was attached to.
// The instance passed to the callback in the second
// argument (`$query`), will be the one where the
// callback is actually being applied to, in this
// example that would be `$articlesQuery`.
// ...
return $results;
});
});
Parameters
- $formatter : callable|null = null
-
The formatting callable.
- $mode : int|bool = self::APPEND
-
Whether to overwrite, append or prepend the formatter.
Tags
Return values
$thisgetIterator()
Executes this query and returns a results iterator. This function is required for implementing the IteratorAggregate interface and allows the query to be iterated without having to call execute() manually, thus making it look like a result set instead of the query itself.
public
getIterator() : ResultSetInterface
Tags
Attributes
- #[ReturnTypeWillChange]
Return values
ResultSetInterfacegetMapReducers()
Returns the list of previously registered map reduce routines.
public
getMapReducers() : array<string|int, mixed>
Return values
array<string|int, mixed>getOptions()
Returns an array with the custom options that were applied to this query and that were not already processed by another method in this class.
public
getOptions() : array<string|int, mixed>
Example:
$query->applyOptions(['doABarrelRoll' => true, 'fields' => ['id', 'name']);
$query->getOptions(); // Returns ['doABarrelRoll' => true]
Tags
Return values
array<string|int, mixed>getRepository()
Returns the default table object that will be used by this query, that is, the table that will appear in the from clause.
public
getRepository() : RepositoryInterface
Return values
RepositoryInterfacegetResultFormatters()
Returns the list of previously registered format routines.
public
getResultFormatters() : array<string|int, callable>
Return values
array<string|int, callable>isEagerLoaded()
Returns the current configured query `_eagerLoaded` value
public
isEagerLoaded() : bool
Return values
boolmapReduce()
Register a new MapReduce routine to be executed on top of the database results Both the mapper and caller callable should be invokable objects.
public
mapReduce([callable|null $mapper = null ][, callable|null $reducer = null ][, bool $overwrite = false ]) : $this
The MapReduce routing will only be run when the query is executed and the first result is attempted to be fetched.
If the third argument is set to true, it will erase previous map reducers and replace it with the arguments passed.
Parameters
- $mapper : callable|null = null
-
The mapper callable.
- $reducer : callable|null = null
-
The reducing function.
- $overwrite : bool = false
-
Set to true to overwrite existing map + reduce functions.
Tags
Return values
$thisrepository()
Set the default Table object that will be used by this query and form the `FROM` clause.
public
repository(RepositoryInterface|Table $repository) : $this
Parameters
- $repository : RepositoryInterface|Table
-
The default table object to use
Return values
$thissetResult()
Set the result set for a query.
public
setResult(iterable<string|int, mixed> $results) : $this
Setting the resultset of a query will make execute() a no-op. Instead of executing the SQL query and fetching results, the ResultSet provided to this method will be returned.
This method is most useful when combined with results stored in a persistent cache.
Parameters
- $results : iterable<string|int, mixed>
-
The results this query should return.
Return values
$thistoArray()
Returns an array representation of the results after executing the query.
public
toArray() : array<string|int, mixed>
Return values
array<string|int, mixed>_decorateResults()
Decorates the results iterator with MapReduce routines and formatters
protected
_decorateResults(Traversable $result) : ResultSetInterface
Parameters
- $result : Traversable
-
Original results
Return values
ResultSetInterface_decoratorClass()
Returns the name of the class to be used for decorating results
protected
_decoratorClass() : string
Tags
Return values
string_execute()
Executes this query and returns a traversable object containing the results
protected
abstract _execute() : ResultSetInterface