Fr3nch13/CakePHP Utilities

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 = []

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
throws
BadMethodCallException

if no such method exists in result set

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
ResultSetInterface

applyOptions()

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
$this

cache()

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
$this

eagerLoaded()

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
$this

first()

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.

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
throws
InvalidArgumentException
Return values
$this

getIterator()

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
psalm-suppress

ImplementedReturnTypeMismatch

Attributes
#[ReturnTypeWillChange]
Return values
ResultSetInterface

getMapReducers()

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
see
QueryInterface::applyOptions()

to read about the options that will be processed by this class and not returned by this function

see
applyOptions()
Return values
array<string|int, mixed>

getResultFormatters()

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
bool

mapReduce()

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
see
MapReduce

for details on how to use emit data to the map reducer.

Return values
$this

setResult()

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
$this

toArray()

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
psalm-return

class-string<\Cake\Datasource\ResultSetInterface>

Return values
string

        
On this page

Search results