CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Team
    • Issues (Github)
    • YouTube Channel
    • Get Involved
    • Bakery
    • Featured Resources
    • Newsletter
    • Certification
    • My CakePHP
    • CakeFest
    • Facebook
    • Twitter
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C CakePHP 3.8 Red Velvet API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 3.8
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Namespaces

  • Cake
    • Auth
      • Storage
    • Cache
      • Engine
    • Collection
      • Iterator
    • Command
    • Console
      • Exception
    • Controller
      • Component
      • Exception
    • Core
      • Configure
        • Engine
      • Exception
      • Retry
    • Database
      • Driver
      • Exception
      • Expression
      • Schema
      • Statement
      • Type
    • Datasource
      • Exception
    • Error
      • Middleware
    • Event
      • Decorator
    • Filesystem
    • Form
    • Http
      • Client
        • Adapter
        • Auth
      • Cookie
      • Exception
      • Middleware
      • Session
    • I18n
      • Formatter
      • Middleware
      • Parser
    • Log
      • Engine
    • Mailer
      • Exception
      • Transport
    • Network
      • Exception
    • ORM
      • Association
      • Behavior
        • Translate
      • Exception
      • Locator
      • Rule
    • Routing
      • Exception
      • Filter
      • Middleware
      • Route
    • Shell
      • Helper
      • Task
    • TestSuite
      • Fixture
      • Stub
    • Utility
      • Exception
    • Validation
    • View
      • Exception
      • Form
      • Helper
      • Widget
  • None

Classes

  • ConnectionManager
  • ConnectionRegistry
  • FactoryLocator
  • Paginator
  • QueryCacher
  • ResultSetDecorator
  • RulesChecker

Interfaces

  • ConnectionInterface
  • EntityInterface
  • FixtureInterface
  • InvalidPropertyInterface
  • PaginatorInterface
  • QueryInterface
  • RepositoryInterface
  • ResultSetInterface
  • SchemaInterface
  • TableSchemaInterface

Traits

  • EntityTrait
  • ModelAwareTrait
  • QueryTrait
  • RulesAwareTrait

Trait QueryTrait

Contains the characteristics for an object that is attached to a repository and can retrieve results based on any criteria.

Direct Users

  • Cake\ORM\Query
Namespace: Cake\Datasource
Location: Datasource/QueryTrait.php

Properties summary

  • $_cache protected
    Cake\Datasource\QueryCacher|null
    A query cacher instance if this query has caching enabled.
  • $_eagerLoaded protected
    boolean
    Whether the query is standalone or the product of an eager load operation.
  • $_formatters protected
    callable[]

    List of formatter classes or callbacks that will post-process the results when fetched

  • $_mapReduce protected
    array

    List of map-reduce routines that should be applied over the query result

  • $_options protected
    array

    Holds any custom options passed using applyOptions that could not be processed by any method in this class.

  • $_repository protected
    Cake\Datasource\RepositoryInterface
    Instance of a table object this query is bound to
  • $_results protected
    Cake\Datasource\ResultSetInterface|null
    A ResultSet.

Method Summary

  • __call() public
    Enables calling methods from the result set as if they were from this class
  • _decorateResults() protected
    Decorates the results iterator with MapReduce routines and formatters
  • _decoratorClass() protected
    Returns the name of the class to be used for decorating results
  • _execute() abstract protected
    Executes this query and returns a traversable object containing the results
  • aliasField() public

    Returns a key => value array representing a single aliased field that can be passed directly to the select() method. The key will contain the alias and the value the actual field name.

  • aliasFields() public

    Runs aliasField() for each field in the provided list and returns the result under a single array.

  • all() public
    Fetch the results for this query.
  • applyOptions() abstract public

    Populates or adds parts to current query clauses using an array. This is handy for passing all query clauses at once.

  • cache() public
    Enable result caching for this query.
  • eagerLoaded() public deprecated

    Sets the query instance to be an eager loaded query. If no argument is passed, the current configured query _eagerLoaded value is returned.

  • first() public

    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() public
    Get the first result from the executing query or raise an exception.
  • formatResults() public

    Registers a new formatter callback function that is to be executed when trying to fetch the results from the database.

  • getIterator() public

    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() public
    Returns the list of previously registered map reduce routines.
  • getOptions() public

    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() public

    Returns the default table object that will be used by this query, that is, the table that will appear in the from clause.

  • getResultFormatters() public
    Returns the list of previously registered format routines.
  • isEagerLoaded() public
    Returns the current configured query _eagerLoaded value
  • mapReduce() public

    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() public

    Returns the default table object that will be used by this query, that is, the table that will appear in the from clause.

  • setResult() public
    Set the result set for a query.
  • toArray() public
    Returns an array representation of the results after executing the query.

Method Detail

__call() public ¶

__call( string $method , array $arguments )

Enables calling methods from the result set as if they were from this class

Parameters
string $method
the method to call
array $arguments
list of arguments for the method to call
Returns
mixed
Throws
BadMethodCallException
if no such method exists in result set

_decorateResults() protected ¶

_decorateResults( Traversable $result )

Decorates the results iterator with MapReduce routines and formatters

Parameters
Traversable $result
Original results
Returns
Cake\Datasource\ResultSetInterface

_decoratorClass() protected ¶

_decoratorClass( )

Returns the name of the class to be used for decorating results

Returns
string

_execute() abstract protected ¶

_execute( )

Executes this query and returns a traversable object containing the results

Returns
Traversable

aliasField() public ¶

aliasField( string $field , string|null $alias = null )

Returns a key => value array representing a single aliased field that can be passed directly to the select() method. 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
string $field
The field to alias
string|null $alias optional null
the alias used to prefix the field
Returns
array

aliasFields() public ¶

aliasFields( array $fields , string|null $defaultAlias = null )

Runs aliasField() for each field in the provided list and returns the result under a single array.

Parameters
array $fields
The fields to alias
string|null $defaultAlias optional null
The default alias
Returns
array

all() public ¶

all( )

Fetch the results for this query.

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.

Returns
Cake\Datasource\ResultSetInterface

applyOptions() abstract public ¶

applyOptions( array $options )

Populates or adds parts to current query clauses using an array. This is handy for passing all query clauses at once.

Parameters
array $options
the options to be applied
Returns

$this

cache() public ¶

cache( Closure|string|false $key , string|Cake\Cache\CacheEngine $config = 'default' )

Enable result caching for this query.

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
Closure|string|false $key

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.

string|Cake\Cache\CacheEngine $config optional 'default'

Either the name of the cache config to use, or a cache config instance.

Returns

$this

eagerLoaded() public deprecated ¶

eagerLoaded( boolean|null $value = null )

Sets the query instance to be an eager loaded query. If no argument is passed, the current configured query _eagerLoaded value is returned.

Deprecated
3.5.0 Use isEagerLoaded() for the getter part instead.
Parameters
boolean|null $value optional null
Whether or not to eager load.
Returns

$this|bool

first() public ¶

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.

Example:

$singleUser = $query->select(['id', 'username'])->first();
Returns
Cake\Datasource\EntityInterface|array|null
The first result from the ResultSet.

firstOrFail() public ¶

firstOrFail( )

Get the first result from the executing query or raise an exception.

Returns
Cake\Datasource\EntityInterface|array
The first result from the ResultSet.
Throws
Cake\Datasource\Exception\RecordNotFoundException
When there is no first record.

formatResults() public ¶

formatResults( callable $formatter = null , boolean|integer $mode = 0 )

Registers a new formatter callback function that is to be executed when trying to fetch the results from the database.

Formatting callbacks will get a first parameter, an object implementing \Cake\Collection\CollectionInterface, that can be traversed and modified at will.

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.

If the first argument is set to null, it will return the list of previously registered format routines. This is deprecated as of 3.6.0 - use getResultFormatters() instead.

If the second argument is set to true, it will erase previous formatters and replace them with the passed first argument.

Example:

// 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;
  });
});
Parameters
callable $formatter optional null
The formatting callable.
boolean|integer $mode optional 0
Whether or not to overwrite, append or prepend the formatter.
Returns

$this|array

getIterator() public ¶

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.

Returns
Iterator

getMapReducers() public ¶

getMapReducers( )

Returns the list of previously registered map reduce routines.

Returns
array

getOptions() public ¶

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.

Example:

$query->applyOptions(['doABarrelRoll' => true, 'fields' => ['id', 'name']);
 $query->getOptions(); // Returns ['doABarrelRoll' => true]
Returns
array
See

\Cake\Datasource\QueryInterface::applyOptions() to read about the options that will be processed by this class and not returned by this function


getRepository() public ¶

getRepository( )

Returns the default table object that will be used by this query, that is, the table that will appear in the from clause.

Returns
Cake\Datasource\RepositoryInterface

getResultFormatters() public ¶

getResultFormatters( )

Returns the list of previously registered format routines.

Returns
array

isEagerLoaded() public ¶

isEagerLoaded( )

Returns the current configured query _eagerLoaded value

Returns
boolean

mapReduce() public ¶

mapReduce( callable $mapper = null , callable $reducer = null , boolean $overwrite = false )

Register a new MapReduce routine to be executed on top of the database results Both the mapper and caller callable should be invokable objects.

The MapReduce routing will only be run when the query is executed and the first result is attempted to be fetched.

If the first argument is set to null, it will return the list of previously registered map reduce routines. This is deprecated as of 3.6.0 - use getMapReducers() instead.

If the third argument is set to true, it will erase previous map reducers and replace it with the arguments passed.

Parameters
callable $mapper optional null
The mapper callable.
callable $reducer optional null
The reducing function.
boolean $overwrite optional false
Set to true to overwrite existing map + reduce functions.
Returns

$this|array
See
\Cake\Collection\Iterator\MapReduce for details on how to use emit data to the map reducer.

repository() public ¶

repository( Cake\Datasource\RepositoryInterface $table = null )

Returns the default table object that will be used by this query, that is, the table that will appear in the from clause.

When called with a Table argument, the default table object will be set and this query object will be returned for chaining.

Parameters
Cake\Datasource\RepositoryInterface $table optional null
The default table object to use
Returns
Cake\Datasource\RepositoryInterface|Cake\Datasource\QueryTrait
$this

setResult() public ¶

setResult( Cake\Datasource\ResultSetInterface $results )

Set the result set for a query.

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
Cake\Datasource\ResultSetInterface $results
The results this query should return.
Returns

$this

toArray() public ¶

toArray( )

Returns an array representation of the results after executing the query.

Returns
array

Properties detail

$_cache ¶

protected Cake\Datasource\QueryCacher|null

A query cacher instance if this query has caching enabled.

$_eagerLoaded ¶

protected boolean

Whether the query is standalone or the product of an eager load operation.

false

$_formatters ¶

protected callable[]

List of formatter classes or callbacks that will post-process the results when fetched

[]

$_mapReduce ¶

protected array

List of map-reduce routines that should be applied over the query result

[]

$_options ¶

protected array

Holds any custom options passed using applyOptions that could not be processed by any method in this class.

[]

$_repository ¶

protected Cake\Datasource\RepositoryInterface

Instance of a table object this query is bound to

$_results ¶

protected Cake\Datasource\ResultSetInterface|null

A ResultSet.

When set, query execution will be bypassed.

See
\Cake\Datasource\QueryTrait::setResult()
Follow @CakePHP
#IRC
OpenHub
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Logos & Trademarks
  • Community
  • Team
  • Issues (Github)
  • YouTube Channel
  • Get Involved
  • Bakery
  • Featured Resources
  • Newsletter
  • Certification
  • My CakePHP
  • CakeFest
  • Facebook
  • Twitter
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs