W3cubDocs

/CakePHP 3.4

Class Query

Extends the base Query class to provide new methods related to association loading, automatic fields selection, automatic type casting and to wrap results into a specific iterator that will be responsible for hydrating results if required.

Cake\Database\Query implements Cake\Database\ExpressionInterface, IteratorAggregate uses Cake\Database\TypeMapTrait
Extended by Cake\ORM\Query implements JsonSerializable, Cake\Datasource\QueryInterface uses Cake\Datasource\QueryTrait
Namespace: Cake\ORM
See: \Cake\Collection\CollectionInterface For a full description of the collection methods supported by this class
Location: ORM/Query.php

Constants summary

Properties summary

  • $_autoFields protected
    boolean

    Tracks whether or not the original query should include fields from the top level table.

  • $_beforeFindFired protected
    boolean
    True if the beforeFind event has already been triggered for this query
  • $_counter protected
    callable

    A callable function that can be used to calculate the total amount of records this query will match when not using limit

  • $_eagerLoader protected

    Instance of a class responsible for storing association containments and for eager loading them when this query is executed

  • $_hasFields protected
    boolean

    Whether the user select any fields before being executed, this is used to determined if any fields should be automatically be selected.

  • $_hydrate protected
    boolean
    Whether to hydrate results into entity objects
  • $_resultsCount protected
    integer|null
    The COUNT(*) for the query.

Inherited Properties

Method Summary

  • __call() public
  • __clone() public
    Object clone hook.
  • __construct() public
    Constructor
  • __debugInfo() public

    Returns an array that can be used to describe the internal state of this object.

  • Used to recursively add contained association column types to the query.

  • Inspects if there are any set fields for selecting, otherwise adds all the fields for the default table.

  • Sets the default types for converting the fields in the select clause
  • _decorateResults() protected
    Decorates the results iterator with MapReduce routines and formatters
  • _dirty() protected

    Marks a query as dirty, removing any preprocessed information from in memory caching such as previous results

  • _execute() protected

    Executes this query and returns a ResultSet object containing the results. This will also setup the correct statement class in order to eager load deep associations.

  • _performCount() protected
    Performs and returns the COUNT(*) for the query.
  • _transformQuery() protected
    Applies some defaults to the query object before it is executed.
  • Hints this object to associate the correct types when casting conditions for the database. This is done by extracting the field types from the schema associated to the passed table object. This prevents the user from repeating himself when specifying conditions.

  • all() public
    Fetch the results for this query.
  • Populates or adds parts to current query clauses using an array. This is handy for passing all query clauses at once. The option array accepts:

  • autoFields() public
    Get/Set whether or not the ORM should automatically append fields.
  • cache() public
  • cleanCopy() public
    Creates a copy of this current query, triggers beforeFind and resets some state.
  • contain() public

    Sets the list of associations that should be eagerly loaded along with this query. The list of associated tables passed must have been previously set as associations using the Table API.

  • count() public
    Returns the total amount of results for the query.
  • counter() public

    Registers a callable function that will be executed when the count method in this query is called. The return value for the function will be set as the return value of the count method.

  • delete() public
    Create a delete query.
  • eagerLoader() public

    Sets the instance of the eager loader class to use for loading associations and storing containments. If called with no arguments, it will return the currently configured instance.

  • Sets whether or not the ORM should automatically append fields.
  • Toggle hydrating entities.
  • find() public
    Apply custom finds to against an existing query object.
  • Returns the currently configured instance.
  • hydrate() public
    Toggle hydrating entities.
  • Creates an INNER JOIN with the passed association table while preserving the foreign key matching and the custom conditions that were originally set for it.

  • insert() public
    Create an insert query.
  • Gets whether or not the ORM should automatically append fields.
  • Returns the current hydration mode.
  • Executes the query and converts the result set into JSON.
  • Creates a LEFT JOIN with the passed association table while preserving the foreign key matching and the custom conditions that were originally set for it.

  • matching() public

    Adds filtering conditions to this query to only bring rows that have a relation to another from an associated table, based on conditions in the associated table.

  • notMatching() public

    Adds filtering conditions to this query to only bring rows that have no match to another from an associated table, based on conditions in the associated table.

  • select() public

    Adds new fields to be returned by a SELECT statement when this query is executed. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string.

  • Sets the instance of the eager loader class to use for loading associations and storing containments.

  • sql() public
    Returns the SQL representation of this object.
  • Trigger the beforeFind event on the query's repository object.
  • update() public
    Create an update query.

Method Detail

__call()source public

__call( $method , $arguments )

Throws

BadMethodCallException
if the method is called for a non-select query

__clone()source public

__clone( )

Object clone hook.

Destroys the clones inner iterator and clones the value binder, and eagerloader instances.

Overrides

Cake\Database\Query::__clone()

__construct()source public

__construct( Cake\Datasource\ConnectionInterface $connection , Cake\ORM\Table $table )

Constructor

Parameters

Cake\Datasource\ConnectionInterface $connection
The connection object
Cake\ORM\Table $table
The table this query is starting on

Overrides

Cake\Database\Query::__construct()

__debugInfo()source public

__debugInfo( )

Returns an array that can be used to describe the internal state of this object.

Returns

array

Overrides

Cake\Database\Query::__debugInfo()

_addAssociationsToTypeMap()source protected

_addAssociationsToTypeMap( Cake\ORM\Table $table , Cake\Database\TypeMap $typeMap , array $associations )

Used to recursively add contained association column types to the query.

Parameters

Cake\ORM\Table $table
The table instance to pluck associations from.
Cake\Database\TypeMap $typeMap

The typemap to check for columns in. This typemap is indirectly mutated via Cake\ORM\Query::addDefaultTypes()

array $associations
The nested tree of associations to walk.

_addDefaultFields()source protected

_addDefaultFields( )

Inspects if there are any set fields for selecting, otherwise adds all the fields for the default table.

_addDefaultSelectTypes()source protected

_addDefaultSelectTypes( )

Sets the default types for converting the fields in the select clause

_decorateResults()source protected

_decorateResults( Traversable $result )

Decorates the results iterator with MapReduce routines and formatters

Parameters

Traversable $result
Original results

Returns

Cake\Datasource\ResultSetInterface

_dirty()source protected

_dirty( )

Marks a query as dirty, removing any preprocessed information from in memory caching such as previous results

Overrides

Cake\Database\Query::_dirty()

_execute()source protected

_execute( )

Executes this query and returns a ResultSet object containing the results. This will also setup the correct statement class in order to eager load deep associations.

Returns

Cake\ORM\ResultSet

_performCount()source protected

_performCount( )

Performs and returns the COUNT(*) for the query.

Returns

integer

_transformQuery()source protected

_transformQuery( )

Applies some defaults to the query object before it is executed.

Specifically add the FROM clause, adds default table fields if none are specified and applies the joins required to eager load associations defined using contain

It also sets the default types for the columns in the select clause

See

\Cake\Database\Query::execute()

addDefaultTypes()source public

addDefaultTypes( Cake\ORM\Table $table )

Hints this object to associate the correct types when casting conditions for the database. This is done by extracting the field types from the schema associated to the passed table object. This prevents the user from repeating himself when specifying conditions.

This method returns the same query object for chaining.

Parameters

Cake\ORM\Table $table
The table to pull types from

Returns


$this

all()source public

all( )

Fetch the results for this query.

Returns

Cake\Datasource\ResultSetInterface

Throws

RuntimeException
if this method is called on a non-select Query.

Implementation of

Cake\Datasource\QueryInterface::all()

applyOptions()source 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. The option array accepts:

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

  • fields: Maps to the select method
  • conditions: Maps to the where method
  • limit: Maps to the limit method
  • order: Maps to the order method
  • offset: Maps to the offset method
  • group: Maps to the group method
  • having: Maps to the having method
  • contain: Maps to the contain options for eager loading
  • join: Maps to the join method
  • page: Maps to the page method

Example:

$query->applyOptions([
  'fields' => ['id', 'name'],
  'conditions' => [
    'created >=' => '2013-01-01'
  ],
  'limit' => 10
]);

Is equivalent to:

$query
  ->select(['id', 'name'])
  ->where(['created >=' => '2013-01-01'])
  ->limit(10)

Parameters

array $options
list of query clauses to apply new parts to.

Returns


$this

Implementation of

Cake\Datasource\QueryInterface::applyOptions()

autoFields()source public

autoFields( boolean|null $value null )

Get/Set whether or not the ORM should automatically append fields.

By default calling select() will disable auto-fields. You can re-enable auto-fields with this method.

Deprecated

3.4.0 Use enableAutoFields()/isAutoFieldsEnabled() instead.

Parameters

boolean|null $value optional null
The value to set or null to read the current value.

Returns

boolean|Cake\ORM\Query
$this Either the current value or the query object.

cache()source public

cache( $key , $config 'default' )

Returns


$this

Throws

RuntimeException
When you attempt to cache a non-select query.

cleanCopy()source public

cleanCopy( )

Creates a copy of this current query, triggers beforeFind and resets some state.

The following state will be cleared:

  • autoFields
  • limit
  • offset
  • map/reduce functions
  • result formatters
  • order
  • containments

This method creates query clones that are useful when working with subqueries.

Returns

Cake\ORM\Query

contain()source public

contain( array|string|null $associations null , boolean $override false )

Sets the list of associations that should be eagerly loaded along with this query. The list of associated tables passed must have been previously set as associations using the Table API.

Example:

// Bring articles' author information
$query->contain('Author');

// Also bring the category and tags associated to each article
$query->contain(['Category', 'Tag']);

Associations can be arbitrarily nested using dot notation or nested arrays, this allows this object to calculate joins or any additional queries that must be executed to bring the required associated data.

Example:

// Eager load the product info, and for each product load other 2 associations
$query->contain(['Product' => ['Manufacturer', 'Distributor']);

// Which is equivalent to calling
$query->contain(['Products.Manufactures', 'Products.Distributors']);

// For an author query, load his region, state and country
$query->contain('Regions.States.Countries');

It is possible to control the conditions and fields selected for each of the contained associations:

Example:

$query->contain(['Tags' => function ($q) {
    return $q->where(['Tags.is_popular' => true]);
}]);

$query->contain(['Products.Manufactures' => function ($q) {
    return $q->select(['name'])->where(['Manufactures.active' => true]);
}]);

Each association might define special options when eager loaded, the allowed options that can be set per association are:

  • foreignKey: Used to set a different field to match both tables, if set to false no join conditions will be generated automatically. false can only be used on joinable associations and cannot be used with hasMany or belongsToMany associations.
  • fields: An array with the fields that should be fetched from the association.
  • finder: The finder to use when loading associated records. Either the name of the finder as a string, or an array to define options to pass to the finder.
  • queryBuilder: Equivalent to passing a callable instead of an options array.

Example:

// Set options for the hasMany articles that will be eagerly loaded for an author
$query->contain([
    'Articles' => [
        'fields' => ['title', 'author_id']
    ]
]);

Finders can be configured to use options.

// Retrieve translations for the articles, but only those for the `en` and `es` locales
$query->contain([
    'Articles' => [
        'finder' => [
            'translations' => [
                'locales' => ['en', 'es']
            ]
        ]
    ]
]);

When containing associations, it is important to include foreign key columns. Failing to do so will trigger exceptions.

// Use special join conditions for getting an Articles's belongsTo 'authors'
$query->contain([
    'Authors' => [
        'foreignKey' => false,
        'queryBuilder' => function ($q) {
            return $q->where(...); // Add full filtering conditions
        }
    ]
]);

If called with no arguments, this function will return an array with with the list of previously configured associations to be contained in the result.

If called with an empty first argument and $override is set to true, the previous list will be emptied.

Parameters

array|string|null $associations optional null
List of table aliases to be queried.
boolean $override optional false

Whether override previous list with the one passed defaults to merging previous list with the new one.

Returns

array|Cake\ORM\Query
$this

count()source public

count( )

Returns the total amount of results for the query.

Returns the COUNT(*) for the query. If the query has not been modified, and the count has already been performed the cached value is returned

Returns

integer

Implementation of

Cake\Datasource\QueryInterface::count()

counter()source public

counter( callable|null $counter )

Registers a callable function that will be executed when the count method in this query is called. The return value for the function will be set as the return value of the count method.

This is particularly useful when you need to optimize a query for returning the count, for example removing unnecessary joins, removing group by or just return an estimated number of rows.

The callback will receive as first argument a clone of this query and not this query itself.

If the first param is a null value, the built-in counter function will be called instead

Parameters

callable|null $counter
The counter value

Returns


$this

delete()source public

delete( string|null $table null )

Create a delete query.

This changes the query type to be 'delete'. Can be combined with the where() method to create delete queries.

Parameters

string|null $table optional null
Unused parameter.

Returns


$this

Overrides

Cake\Database\Query::delete()

eagerLoader()source public

eagerLoader( Cake\ORM\EagerLoader $instance null )

Sets the instance of the eager loader class to use for loading associations and storing containments. If called with no arguments, it will return the currently configured instance.

Deprecated

3.4.0 Use setEagerLoader()/getEagerLoader() instead.

Parameters

Cake\ORM\EagerLoader $instance optional null

The eager loader to use. Pass null to get the current eagerloader.

Returns

Cake\ORM\EagerLoader|Cake\ORM\Query
$this

enableAutoFields()source public

enableAutoFields( boolean $value true )

Sets whether or not the ORM should automatically append fields.

By default calling select() will disable auto-fields. You can re-enable auto-fields with this method.

Parameters

boolean $value optional true
Set true to enable, false to disable.

Returns


$this

enableHydration()source public

enableHydration( boolean $enable true )

Toggle hydrating entities.

If set to false array results will be returned for the query.

Parameters

boolean $enable optional true
Use a boolean to set the hydration mode.

Returns


$this

find()source public

find( string $finder , array $options [] )

Apply custom finds to against an existing query object.

Parameters

string $finder
The finder method to use.
array $options optional []
The options for the finder.

Returns


$this Returns a modified query.

See

\Cake\ORM\Table::find()

Implementation of

Cake\Datasource\QueryInterface::find()

getEagerLoader()source public

getEagerLoader( )

Returns the currently configured instance.

Returns

Cake\ORM\EagerLoader

hydrate()source public

hydrate( boolean|null $enable null )

Toggle hydrating entities.

If set to false array results will be returned.

Deprecated

3.4.0 Use enableHydration()/isHydrationEnabled() instead.

Parameters

boolean|null $enable optional null

Use a boolean to set the hydration mode. Null will fetch the current hydration mode.

Returns

boolean|Cake\ORM\Query
$this A boolean when reading, and $this when setting the mode.

innerJoinWith()source public

innerJoinWith( string $assoc , callable $builder null )

Creates an INNER JOIN with the passed association table while preserving the foreign key matching and the custom conditions that were originally set for it.

This function will add entries in the contain graph.

Example:

// Bring only articles that were tagged with 'cake'
$query->innerJoinWith('Tags', function ($q) {
    return $q->where(['name' => 'cake']);
);

This will create the following SQL:

SELECT Articles.*
FROM articles Articles
INNER JOIN tags Tags ON Tags.name = 'cake'
INNER JOIN articles_tags ArticlesTags ON ArticlesTags.tag_id = Tags.id
  AND ArticlesTags.articles_id = Articles.id

This function works the same as matching() with the difference that it will select no fields from the association.

Parameters

string $assoc
The association to join with
callable $builder optional null

a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields

Returns


$this

See

\Cake\ORM\Query::matching()

insert()source public

insert( array $columns , array $types [] )

Create an insert query.

This changes the query type to be 'insert'. Note calling this method will reset any data previously set with Query::values()

Can be combined with the where() method to create delete queries.

Parameters

array $columns
The columns to insert into.
array $types optional []
A map between columns & their datatypes.

Returns


$this

Throws

RuntimeException
When there are 0 columns.

Overrides

Cake\Database\Query::insert()

isAutoFieldsEnabled()source public

isAutoFieldsEnabled( )

Gets whether or not the ORM should automatically append fields.

By default calling select() will disable auto-fields. You can re-enable auto-fields with enableAutoFields().

Returns

boolean
The current value.

isHydrationEnabled()source public

isHydrationEnabled( )

Returns the current hydration mode.

Returns

boolean

jsonSerialize()source public

jsonSerialize( )

Executes the query and converts the result set into JSON.

Part of JsonSerializable interface.

Returns

Cake\Datasource\ResultSetInterface
The data to convert to JSON.

Implementation of

JsonSerializable::jsonSerialize()

leftJoinWith()source public

leftJoinWith( string $assoc , callable $builder null )

Creates a LEFT JOIN with the passed association table while preserving the foreign key matching and the custom conditions that were originally set for it.

This function will add entries in the contain graph.

Example:

// Get the count of articles per user
$usersQuery
    ->select(['total_articles' => $query->func()->count('Articles.id')])
    ->leftJoinWith('Articles')
    ->group(['Users.id'])
    ->enableAutoFields(true);

You can also customize the conditions passed to the LEFT JOIN:

// Get the count of articles per user with at least 5 votes
$usersQuery
    ->select(['total_articles' => $query->func()->count('Articles.id')])
    ->leftJoinWith('Articles', function ($q) {
        return $q->where(['Articles.votes >=' => 5]);
    })
    ->group(['Users.id'])
    ->enableAutoFields(true);

This will create the following SQL:

SELECT COUNT(Articles.id) AS total_articles, Users.*
FROM users Users
LEFT JOIN articles Articles ON Articles.user_id = Users.id AND Articles.votes >= 5
GROUP BY USers.id

It is possible to left join deep associations by using dot notation

Example:

// Total comments in articles by 'markstory'
$query
 ->select(['total_comments' => $query->func()->count('Comments.id')])
 ->leftJoinWith('Comments.Users', function ($q) {
    return $q->where(['username' => 'markstory']);
)
->group(['Users.id']);

Please note that the query passed to the closure will only accept calling select, where, andWhere and orWhere on it. If you wish to add more complex clauses you can do it directly in the main query.

Parameters

string $assoc
The association to join with
callable $builder optional null

a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields

Returns


$this

matching()source public

matching( string $assoc , callable $builder null )

Adds filtering conditions to this query to only bring rows that have a relation to another from an associated table, based on conditions in the associated table.

This function will add entries in the contain graph.

Example:

// Bring only articles that were tagged with 'cake'
$query->matching('Tags', function ($q) {
    return $q->where(['name' => 'cake']);
);

It is possible to filter by deep associations by using dot notation:

Example:

// Bring only articles that were commented by 'markstory'
$query->matching('Comments.Users', function ($q) {
    return $q->where(['username' => 'markstory']);
);

As this function will create INNER JOIN, you might want to consider calling distinct on this query as you might get duplicate rows if your conditions don't filter them already. This might be the case, for example, of the same user commenting more than once in the same article.

Example:

// Bring unique articles that were commented by 'markstory'
$query->distinct(['Articles.id'])
->matching('Comments.Users', function ($q) {
    return $q->where(['username' => 'markstory']);
);

Please note that the query passed to the closure will only accept calling select, where, andWhere and orWhere on it. If you wish to add more complex clauses you can do it directly in the main query.

Parameters

string $assoc
The association to filter by
callable $builder optional null

a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields

Returns


$this

notMatching()source public

notMatching( string $assoc , callable $builder null )

Adds filtering conditions to this query to only bring rows that have no match to another from an associated table, based on conditions in the associated table.

This function will add entries in the contain graph.

Example:

// Bring only articles that were not tagged with 'cake'
$query->notMatching('Tags', function ($q) {
    return $q->where(['name' => 'cake']);
);

It is possible to filter by deep associations by using dot notation:

Example:

// Bring only articles that weren't commented by 'markstory'
$query->notMatching('Comments.Users', function ($q) {
    return $q->where(['username' => 'markstory']);
);

As this function will create a LEFT JOIN, you might want to consider calling distinct on this query as you might get duplicate rows if your conditions don't filter them already. This might be the case, for example, of the same article having multiple comments.

Example:

// Bring unique articles that were commented by 'markstory'
$query->distinct(['Articles.id'])
->notMatching('Comments.Users', function ($q) {
    return $q->where(['username' => 'markstory']);
);

Please note that the query passed to the closure will only accept calling select, where, andWhere and orWhere on it. If you wish to add more complex clauses you can do it directly in the main query.

Parameters

string $assoc
The association to filter by
callable $builder optional null

a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields

Returns


$this

select()source public

select( array|Cake\Database\ExpressionInterface|string|Cake\ORM\Table|Cake\ORM\Association $fields [] , boolean $overwrite false )

Adds new fields to be returned by a SELECT statement when this query is executed. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string.

If you pass an instance of a Cake\ORM\Table or Cake\ORM\Association class, all the fields in the schema of the table or the association will be added to the select clause.

Parameters

array|Cake\Database\ExpressionInterface|string|Cake\ORM\Table|Cake\ORM\Association $fields optional []

fields to be added to the list.

boolean $overwrite optional false
whether to reset fields with passed list or not

Returns


$this

Overrides

Cake\Database\Query::select()

setEagerLoader()source public

setEagerLoader( Cake\ORM\EagerLoader $instance )

Sets the instance of the eager loader class to use for loading associations and storing containments.

Parameters

Cake\ORM\EagerLoader $instance
The eager loader to use.

Returns


$this

sql()source public

sql( Cake\Database\ValueBinder $binder null )

Returns the SQL representation of this object.

Parameters

Cake\Database\ValueBinder $binder optional null

$generator A placeholder object that will hold associated values for expressions

Returns

string

Overrides

Cake\Database\Query::sql()

triggerBeforeFind()source public

triggerBeforeFind( )

Trigger the beforeFind event on the query's repository object.

Will not trigger more than once, and only for select queries.

update()source public

update( string|null $table null )

Create an update query.

This changes the query type to be 'update'. Can be combined with set() and where() methods to create update queries.

Parameters

string|null $table optional null
Unused parameter.

Returns


$this

Overrides

Cake\Database\Query::update()

Methods inherited from Cake\Database\Query

__toString()source public

__toString( )

Returns string representation of this query (complete SQL statement).

Returns

string

_conjugate()source protected

_conjugate( string $part , string|null|array|Cake\Database\ExpressionInterface|callable $append , string $conjunction , array $types )

Helper function used to build conditions by composing QueryExpression objects.

Parameters

string $part
Name of the query part to append the new part to
string|null|array|Cake\Database\ExpressionInterface|callable $append
Expression or builder function to append.
string $conjunction
type of conjunction to be used to operate part
array $types
associative array of type names used to bind values to query

_decorateStatement()source protected

_decorateStatement( Cake\Database\StatementInterface $statement )

Auxiliary function used to wrap the original statement from the driver with any registered callbacks.

Parameters

Cake\Database\StatementInterface $statement
to be decorated

Returns

Cake\Database\Statement\CallbackStatement

_makeJoin()source protected

_makeJoin( string|array $table , string|array|Cake\Database\ExpressionInterface $conditions , string $type )

Returns an array that can be passed to the join method describing a single join clause

Parameters

string|array $table
The table to join with
string|array|Cake\Database\ExpressionInterface $conditions

The conditions to use for joining.

string $type
the join type to use

Returns

array

andHaving()source public

andHaving( string|array|Cake\Database\ExpressionInterface|callable $conditions , array $types [] )

Connects any previously defined set of conditions to the provided list using the AND operator in the HAVING clause. This method operates in exactly the same way as the method andWhere() does. Please refer to its documentation for an insight on how to using each parameter.

Parameters

string|array|Cake\Database\ExpressionInterface|callable $conditions
The AND conditions for HAVING.
array $types optional []
associative array of type names used to bind values to query

Returns


$this

See

\Cake\Database\Query::andWhere()

andWhere()source public

andWhere( string|array|Cake\Database\ExpressionInterface|callable $conditions , array $types [] )

Connects any previously defined set of conditions to the provided list using the AND operator. This function accepts the conditions list in the same format as the method where does, hence you can use arrays, expression objects callback functions or strings.

It is important to notice that when calling this function, any previous set of conditions defined for this query will be treated as a single argument for the AND operator. This function will not only operate the most recently defined condition, but all the conditions as a whole.

When using an array for defining conditions, creating constraints form each array entry will use the same logic as with the where() function. This means that each array entry will be joined to the other using the AND operator, unless you nest the conditions in the array using other operator.

Examples:

$query->where(['title' => 'Hello World')->andWhere(['author_id' => 1]);

Will produce:

WHERE title = 'Hello World' AND author_id = 1

$query
  ->where(['OR' => ['published' => false, 'published is NULL']])
  ->andWhere(['author_id' => 1, 'comments_count >' => 10])

Produces:

WHERE (published = 0 OR published IS NULL) AND author_id = 1 AND comments_count > 10

$query
  ->where(['title' => 'Foo'])
  ->andWhere(function ($exp, $query) {
    return $exp
      ->add(['author_id' => 1])
      ->or_(['author_id' => 2]);
  });

Generates the following conditions:

WHERE (title = 'Foo') AND (author_id = 1 OR author_id = 2)

Parameters

string|array|Cake\Database\ExpressionInterface|callable $conditions
The conditions to add with AND.
array $types optional []
associative array of type names used to bind values to query

Returns


$this

See

\Cake\Database\Query::where()
Cake\Database\Type

bind()source public

bind( string|integer $param , mixed $value , string|integer $type 'string' )

Associates a query placeholder to a value and a type.

If type is expressed as "atype[]" (note braces) then it will cause the placeholder to be re-written dynamically so if the value is an array, it will create as many placeholders as values are in it. For example:

$query->bind(':id', [1, 2, 3], 'int[]');

Will create 3 int placeholders. When using named placeholders, this method requires that the placeholders include : e.g. :value.

Parameters

string|integer $param

placeholder to be replaced with quoted version of $value

mixed $value
The value to be bound
string|integer $type optional 'string'

the mapped type name, used for casting when sending to database

Returns


$this

bufferResults()source public

bufferResults( boolean|null $enable null )

Enable/Disable buffered results.

When enabled the results returned by this Query will be buffered. This enables you to iterate a result set multiple times, or both cache and iterate it.

When disabled it will consume less memory as fetched results are not remembered for future iterations.

If called with no arguments, it will return whether or not buffering is enabled.

Deprecated

3.4.0 Use enableBufferedResults()/isBufferedResultsEnabled() instead.

Parameters

boolean|null $enable optional null
Whether or not to enable buffering

Returns

boolean|Cake\Database\Query
$this

clause()source public

clause( string $name )

Returns any data that was stored in the specified clause. This is useful for modifying any internal part of the query and it is used by the SQL dialects to transform the query accordingly before it is executed. The valid clauses that can be retrieved are: delete, update, set, insert, values, select, distinct, from, join, set, where, group, having, order, limit, offset and union.

The return value for each of those parts may vary. Some clauses use QueryExpression to internally store their state, some use arrays and others may use booleans or integers. This is summary of the return types for each clause.

  • update: string The name of the table to update
  • set: QueryExpression
  • insert: array, will return an array containing the table + columns.
  • values: ValuesExpression
  • select: array, will return empty array when no fields are set
  • distinct: boolean
  • from: array of tables
  • join: array
  • set: array
  • where: QueryExpression, returns null when not set
  • group: array
  • having: QueryExpression, returns null when not set
  • order: OrderByExpression, returns null when not set
  • limit: integer or QueryExpression, null when not set
  • offset: integer or QueryExpression, null when not set
  • union: array

Parameters

string $name
name of the clause to be returned

Returns

mixed

connection()source public

connection( Cake\Datasource\ConnectionInterface|null $connection null )

Sets the connection instance to be used for executing and transforming this query When called with a null argument, it will return the current connection instance.

Deprecated

3.4.0 Use setConnection()/getConnection() instead.

Parameters

Cake\Datasource\ConnectionInterface|null $connection optional null
Connection instance

Returns


$this|\Cake\Datasource\ConnectionInterface

decorateResults()source public

decorateResults( callable|null $callback , boolean $overwrite false )

Registers a callback to be executed for each result that is fetched from the result set, the callback function will receive as first parameter an array with the raw data from the database for every row that is fetched and must return the row with any possible modifications.

Callbacks will be executed lazily, if only 3 rows are fetched for database it will called 3 times, event though there might be more rows to be fetched in the cursor.

Callbacks are stacked in the order they are registered, if you wish to reset the stack the call this function with the second parameter set to true.

If you wish to remove all decorators from the stack, set the first parameter to null and the second to true.

Example

$query->decorateResults(function ($row) {
  $row['order_total'] = $row['subtotal'] + ($row['subtotal'] * $row['tax']);
   return $row;
});

Parameters

callable|null $callback
The callback to invoke when results are fetched.
boolean $overwrite optional false
Whether or not this should append or replace all existing decorators.

Returns


$this

distinct()source public

distinct( array|Cake\Database\ExpressionInterface|string|boolean $on [] , boolean $overwrite false )

Adds a DISTINCT clause to the query to remove duplicates from the result set. This clause can only be used for select statements.

If you wish to filter duplicates based of those rows sharing a particular field or set of fields, you may pass an array of fields to filter on. Beware that this option might not be fully supported in all database systems.

Examples:

// Filters products with the same name and city
$query->select(['name', 'city'])->from('products')->distinct();

// Filters products in the same city
$query->distinct(['city']);
$query->distinct('city');

// Filter products with the same name
$query->distinct(['name'], true);
$query->distinct('name', true);

Parameters

array|Cake\Database\ExpressionInterface|string|boolean $on optional []

Enable/disable distinct class or list of fields to be filtered on

boolean $overwrite optional false
whether to reset fields with passed list or not

Returns


$this

enableBufferedResults()source public

enableBufferedResults( boolean $enable true )

Enables/Disables buffered results.

When enabled the results returned by this Query will be buffered. This enables you to iterate a result set multiple times, or both cache and iterate it.

When disabled it will consume less memory as fetched results are not remembered for future iterations.

Parameters

boolean $enable optional true
Whether or not to enable buffering

Returns


$this

epilog()source public

epilog( string|Cake\Database\Expression\QueryExpression|null $expression null )

A string or expression that will be appended to the generated query

Examples:

$query->select('id')->where(['author_id' => 1])->epilog('FOR UPDATE');
$query
 ->insert('articles', ['title'])
 ->values(['author_id' => 1])
 ->epilog('RETURNING id');

Parameters

string|Cake\Database\Expression\QueryExpression|null $expression optional null
The expression to be appended

Returns


$this

execute()source public

execute( )

Compiles the SQL representation of this query and executes it using the configured connection object. Returns the resulting statement object.

Executing a query internally executes several steps, the first one is letting the connection transform this object to fit its particular dialect, this might result in generating a different Query object that will be the one to actually be executed. Immediately after, literal values are passed to the connection so they are bound to the query in a safe way. Finally, the resulting statement is decorated with custom objects to execute callbacks for each row retrieved if necessary.

Resulting statement is traversable, so it can be used in any loop as you would with an array.

This method can be overridden in query subclasses to decorate behavior around query execution.

Returns

Cake\Database\StatementInterface

from()source public

from( array|string $tables [] , boolean $overwrite false )

Adds a single or multiple tables to be used in the FROM clause for this query. Tables can be passed as an array of strings, array of expression objects, a single expression or a single string.

If an array is passed, keys will be used to alias tables using the value as the real field to be aliased. It is possible to alias strings, ExpressionInterface objects or even other Query objects.

By default this function will append any passed argument to the list of tables to be selected from, unless the second argument is set to true.

This method can be used for select, update and delete statements.

Examples:

$query->from(['p' => 'posts']); // Produces FROM posts p
$query->from('authors'); // Appends authors: FROM posts p, authors
$query->from(['products'], true); // Resets the list: FROM products
$query->from(['sub' => $countQuery]); // FROM (SELECT ...) sub

Parameters

array|string $tables optional []

tables to be added to the list. This argument, can be passed as an array of strings, array of expression objects, or a single string. See the examples above for the valid call types.

boolean $overwrite optional false
whether to reset tables with passed list or not

Returns


$this|array

func()source public

func( )

Returns an instance of a functions builder object that can be used for generating arbitrary SQL functions.

Example:

$query->func()->count('*');
$query->func()->dateDiff(['2012-01-05', '2012-01-02'])

Returns

Cake\Database\FunctionsBuilder

getConnection()source public

getConnection( )

Gets the connection instance to be used for executing and transforming this query.

Returns

Cake\Datasource\ConnectionInterface

getIterator()source 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

Cake\Database\StatementInterface|null

Implementation of

IteratorAggregate::getIterator()

getSelectTypeMap()source public

getSelectTypeMap( )

Gets the TypeMap class where the types for each of the fields in the select clause are stored.

Returns

Cake\Database\TypeMap

group()source public

group( array|Cake\Database\ExpressionInterface|string $fields , boolean $overwrite false )

Adds a single or multiple fields to be used in the GROUP BY clause for this query. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string.

By default this function will append any passed argument to the list of fields to be grouped, unless the second argument is set to true.

Examples:

// Produces GROUP BY id, title
$query->group(['id', 'title']);

// Produces GROUP BY title
$query->group('title');

Parameters

array|Cake\Database\ExpressionInterface|string $fields
fields to be added to the list
boolean $overwrite optional false
whether to reset fields with passed list or not

Returns


$this

having()source public

having( string|array|Cake\Database\ExpressionInterface|callable|null $conditions null , array $types [] , boolean $overwrite false )

Adds a condition or set of conditions to be used in the HAVING clause for this query. This method operates in exactly the same way as the method where() does. Please refer to its documentation for an insight on how to using each parameter.

Parameters

string|array|Cake\Database\ExpressionInterface|callable|null $conditions optional null
The having conditions.
array $types optional []
associative array of type names used to bind values to query
boolean $overwrite optional false
whether to reset conditions with passed list or not

Returns


$this

See

\Cake\Database\Query::where()

innerJoin()source public

innerJoin( string|array $table , string|array|Cake\Database\ExpressionInterface $conditions [] , array $types [] )

Adds a single INNER JOIN clause to the query.

This is a shorthand method for building joins via join().

The arguments of this method are identical to the leftJoin() shorthand, please refer to that methods description for further details.

Parameters

string|array $table
The table to join with
string|array|Cake\Database\ExpressionInterface $conditions optional []

The conditions to use for joining.

array $types optional []

a list of types associated to the conditions used for converting values to the corresponding database representation.

Returns


$this

into()source public

into( string $table )

Set the table name for insert queries.

Parameters

string $table
The table name to insert into.

Returns


$this

isBufferedResultsEnabled()source public

isBufferedResultsEnabled( )

Returns whether buffered results are enabled/disabled.

When enabled the results returned by this Query will be buffered. This enables you to iterate a result set multiple times, or both cache and iterate it.

When disabled it will consume less memory as fetched results are not remembered for future iterations.

Returns

boolean

join()source public

join( array|string|null $tables null , array $types [] , boolean $overwrite false )

Adds a single or multiple tables to be used as JOIN clauses to this query. Tables can be passed as an array of strings, an array describing the join parts, an array with multiple join descriptions, or a single string.

By default this function will append any passed argument to the list of tables to be joined, unless the third argument is set to true.

When no join type is specified an INNER JOIN is used by default: $query->join(['authors']) will produce INNER JOIN authors ON 1 = 1

It is also possible to alias joins using the array key: $query->join(['a' => 'authors'])`` will produceINNER JOIN authors a ON 1 = 1`

A join can be fully described and aliased using the array notation:

$query->join([
    'a' => [
        'table' => 'authors',
        'type' => 'LEFT',
        'conditions' => 'a.id = b.author_id'
    ]
]);
// Produces LEFT JOIN authors a ON a.id = b.author_id

You can even specify multiple joins in an array, including the full description:

$query->join([
    'a' => [
        'table' => 'authors',
        'type' => 'LEFT',
        'conditions' => 'a.id = b.author_id'
    ],
    'p' => [
        'table' => 'publishers',
        'type' => 'INNER',
        'conditions' => 'p.id = b.publisher_id AND p.name = "Cake Software Foundation"'
    ]
]);
// LEFT JOIN authors a ON a.id = b.author_id
// INNER JOIN publishers p ON p.id = b.publisher_id AND p.name = "Cake Software Foundation"

Using conditions and types

Conditions can be expressed, as in the examples above, using a string for comparing columns, or string with already quoted literal values. Additionally it is possible to use conditions expressed in arrays or expression objects.

When using arrays for expressing conditions, it is often desirable to convert the literal values to the correct database representation. This is achieved using the second parameter of this function.

$query->join(['a' => [
    'table' => 'articles',
    'conditions' => [
        'a.posted >=' => new DateTime('-3 days'),
        'a.published' => true,
        'a.author_id = authors.id'
    ]
]], ['a.posted' => 'datetime', 'a.published' => 'boolean'])

Overwriting joins

When creating aliased joins using the array notation, you can override previous join definitions by using the same alias in consequent calls to this function or you can replace all previously defined joins with another list if the third parameter for this function is set to true.

$query->join(['alias' => 'table']); // joins table with as alias
$query->join(['alias' => 'another_table']); // joins another_table with as alias
$query->join(['something' => 'different_table'], [], true); // resets joins list

Parameters

array|string|null $tables optional null
list of tables to be joined in the query
array $types optional []
associative array of type names used to bind values to query
boolean $overwrite optional false
whether to reset joins with passed list or not

Returns


$this|array

See

Cake\Database\Type

leftJoin()source public

leftJoin( string|array $table , string|array|Cake\Database\ExpressionInterface $conditions [] , array $types [] )

Adds a single LEFT JOIN clause to the query.

This is a shorthand method for building joins via join().

The table name can be passed as a string, or as an array in case it needs to be aliased:

// LEFT JOIN authors ON authors.id = posts.author_id
$query->leftJoin('authors', 'authors.id = posts.author_id');

// LEFT JOIN authors a ON a.id = posts.author_id
$query->leftJoin(['a' => 'authors'], 'a.id = posts.author_id');

Conditions can be passed as strings, arrays, or expression objects. When using arrays it is possible to combine them with the $types parameter in order to define how to convert the values:

$query->leftJoin(['a' => 'articles'], [
     'a.posted >=' => new DateTime('-3 days'),
     'a.published' => true,
     'a.author_id = authors.id'
], ['a.posted' => 'datetime', 'a.published' => 'boolean']);

See join() for further details on conditions and types.

Parameters

string|array $table
The table to join with
string|array|Cake\Database\ExpressionInterface $conditions optional []

The conditions to use for joining.

array $types optional []

a list of types associated to the conditions used for converting values to the corresponding database representation.

Returns


$this

limit()source public

limit( integer|Cake\Database\ExpressionInterface $num )

Sets the number of records that should be retrieved from database, accepts an integer or an expression object that evaluates to an integer. In some databases, this operation might not be supported or will require the query to be transformed in order to limit the result set size.

Examples

$query->limit(10) // generates LIMIT 10
$query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)

Parameters

integer|Cake\Database\ExpressionInterface $num
number of records to be returned

Returns


$this

modifier()source public

modifier( array|Cake\Database\ExpressionInterface|string $modifiers , boolean $overwrite false )

Adds a single or multiple SELECT modifiers to be used in the SELECT.

By default this function will append any passed argument to the list of modifiers to be applied, unless the second argument is set to true.

Example:

// Ignore cache query in MySQL
$query->select(['name', 'city'])->from('products')->modifier('SQL_NO_CACHE');
// It will produce the SQL: SELECT SQL_NO_CACHE name, city FROM products

// Or with multiple modifiers
$query->select(['name', 'city'])->from('products')->modifier(['HIGH_PRIORITY', 'SQL_NO_CACHE']);
// It will produce the SQL: SELECT HIGH_PRIORITY SQL_NO_CACHE name, city FROM products

Parameters

array|Cake\Database\ExpressionInterface|string $modifiers
modifiers to be applied to the query
boolean $overwrite optional false
whether to reset order with field list or not

Returns


$this

newExpr()source public

newExpr( mixed $rawExpression null )

Returns a new QueryExpression object. This is a handy function when building complex queries using a fluent interface. You can also override this function in subclasses to use a more specialized QueryExpression class if required.

You can optionally pass a single raw SQL string or an array or expressions in any format accepted by \Cake\Database\Expression\QueryExpression:

$expression = $query->newExpr(); // Returns an empty expression object
$expression = $query->newExpr('Table.column = Table2.column'); // Return a raw SQL expression

Parameters

mixed $rawExpression optional null
A string, array or anything you want wrapped in an expression object

Returns

Cake\Database\Expression\QueryExpression

offset()source public

offset( integer|Cake\Database\ExpressionInterface $num )

Sets the number of records that should be skipped from the original result set This is commonly used for paginating large results. Accepts an integer or an expression object that evaluates to an integer.

In some databases, this operation might not be supported or will require the query to be transformed in order to limit the result set size.

Examples

$query->offset(10) // generates OFFSET 10
$query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)

Parameters

integer|Cake\Database\ExpressionInterface $num
number of records to be skipped

Returns


$this

orHaving()source public

orHaving( string|array|Cake\Database\ExpressionInterface|callable $conditions , array $types [] )

Connects any previously defined set of conditions to the provided list using the OR operator in the HAVING clause. This method operates in exactly the same way as the method orWhere() does. Please refer to its documentation for an insight on how to using each parameter.

Parameters

string|array|Cake\Database\ExpressionInterface|callable $conditions
The OR conditions for HAVING.
array $types optional []
associative array of type names used to bind values to query.

Returns


$this

See

\Cake\Database\Query::orWhere()

orWhere()source public

orWhere( string|array|Cake\Database\ExpressionInterface|callable $conditions , array $types [] )

Connects any previously defined set of conditions to the provided list using the OR operator. This function accepts the conditions list in the same format as the method where does, hence you can use arrays, expression objects callback functions or strings.

It is important to notice that when calling this function, any previous set of conditions defined for this query will be treated as a single argument for the OR operator. This function will not only operate the most recently defined condition, but all the conditions as a whole.

When using an array for defining conditions, creating constraints form each array entry will use the same logic as with the where() function. This means that each array entry will be joined to the other using the OR operator, unless you nest the conditions in the array using other operator.

Examples:

$query->where(['title' => 'Hello World')->orWhere(['title' => 'Foo']);

Will produce:

WHERE title = 'Hello World' OR title = 'Foo'

$query
  ->where(['OR' => ['published' => false, 'published is NULL']])
  ->orWhere(['author_id' => 1, 'comments_count >' => 10])

Produces:

WHERE (published = 0 OR published IS NULL) OR (author_id = 1 AND comments_count > 10)

$query
  ->where(['title' => 'Foo'])
  ->orWhere(function ($exp, $query) {
    return $exp
      ->add(['author_id' => 1])
      ->or_(['author_id' => 2]);
  });

Generates the following conditions:

WHERE (title = 'Foo') OR (author_id = 1 OR author_id = 2)

Parameters

string|array|Cake\Database\ExpressionInterface|callable $conditions
The conditions to add with OR.
array $types optional []
associative array of type names used to bind values to query

Returns


$this

See

\Cake\Database\Query::where()
Cake\Database\Type

order()source public

order( array|Cake\Database\ExpressionInterface|string $fields , boolean $overwrite false )

Adds a single or multiple fields to be used in the ORDER clause for this query. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string.

If an array is passed, keys will be used as the field itself and the value will represent the order in which such field should be ordered. When called multiple times with the same fields as key, the last order definition will prevail over the others.

By default this function will append any passed argument to the list of fields to be selected, unless the second argument is set to true.

Examples:

$query->order(['title' => 'DESC', 'author_id' => 'ASC']);

Produces:

ORDER BY title DESC, author_id ASC

$query->order(['title' => 'DESC NULLS FIRST'])->order('author_id');

Will generate:

ORDER BY title DESC NULLS FIRST, author_id

$expression = $query->newExpr()->add(['id % 2 = 0']);
$query->order($expression)->order(['title' => 'ASC']);

Will become:

ORDER BY (id %2 = 0), title ASC

If you need to set complex expressions as order conditions, you should use orderAsc() or orderDesc().

Parameters

array|Cake\Database\ExpressionInterface|string $fields
fields to be added to the list
boolean $overwrite optional false
whether to reset order with field list or not

Returns


$this

orderAsc()source public

orderAsc( string|Cake\Database\Expression\QueryExpression $field , boolean $overwrite false )

Add an ORDER BY clause with an ASC direction.

This method allows you to set complex expressions as order conditions unlike order()

Parameters

string|Cake\Database\Expression\QueryExpression $field
The field to order on.
boolean $overwrite optional false
Whether or not to reset the order clauses.

Returns


$this

orderDesc()source public

orderDesc( string|Cake\Database\Expression\QueryExpression $field , boolean $overwrite false )

Add an ORDER BY clause with a DESC direction.

This method allows you to set complex expressions as order conditions unlike order()

Parameters

string|Cake\Database\Expression\QueryExpression $field
The field to order on.
boolean $overwrite optional false
Whether or not to reset the order clauses.

Returns


$this

page()source public

page( integer $num , integer|null $limit null )

Set the page of results you want.

This method provides an easier to use interface to set the limit + offset in the record set you want as results. If empty the limit will default to the existing limit clause, and if that too is empty, then 25 will be used.

Pages should start at 1.

Parameters

integer $num
The page number you want.
integer|null $limit optional null

The number of rows you want in the page. If null the current limit clause will be used.

Returns


$this

removeJoin()source public

removeJoin( string $name )

Remove a join if it has been defined.

Useful when you are redefining joins or want to re-order the join clauses.

Parameters

string $name
The alias/name of the join to remove.

Returns


$this

rightJoin()source public

rightJoin( string|array $table , string|array|Cake\Database\ExpressionInterface $conditions [] , array $types [] )

Adds a single RIGHT JOIN clause to the query.

This is a shorthand method for building joins via join().

The arguments of this method are identical to the leftJoin() shorthand, please refer to that methods description for further details.

Parameters

string|array $table
The table to join with
string|array|Cake\Database\ExpressionInterface $conditions optional []

The conditions to use for joining.

array $types optional []

a list of types associated to the conditions used for converting values to the corresponding database representation.

Returns


$this

selectTypeMap()source public

selectTypeMap( Cake\Database\TypeMap $typeMap null )

Sets the TypeMap class where the types for each of the fields in the select clause are stored.

When called with no arguments, the current TypeMap object is returned.

Deprecated

3.4.0 Use setSelectTypeMap()/getSelectTypeMap() instead.

Parameters

Cake\Database\TypeMap $typeMap optional null
The map object to use

Returns


$this|\Cake\Database\TypeMap

set()source public

set( string|array|callable|Cake\Database\Expression\QueryExpression $key , mixed $value null , array $types [] )

Set one or many fields to update.

Examples

Passing a string:

$query->update('articles')->set('title', 'The Title');

Passing an array:

$query->update('articles')->set(['title' => 'The Title'], ['title' => 'string']);

Passing a callable:

$query->update('articles')->set(function ($exp) {
  return $exp->eq('title', 'The title', 'string');
});

Parameters

string|array|callable|Cake\Database\Expression\QueryExpression $key

The column name or array of keys + values to set. This can also be a QueryExpression containing a SQL fragment. It can also be a callable, that is required to return an expression object.

mixed $value optional null

The value to update $key to. Can be null if $key is an array or QueryExpression. When $key is an array, this parameter will be used as $types instead.

array $types optional []
The column types to treat data as.

Returns


$this

setConnection()source public

setConnection( Cake\Datasource\ConnectionInterface $connection )

Sets the connection instance to be used for executing and transforming this query.

Parameters

Cake\Datasource\ConnectionInterface $connection
Connection instance

Returns


$this

setSelectTypeMap()source public

setSelectTypeMap( Cake\Database\TypeMap $typeMap )

Sets the TypeMap class where the types for each of the fields in the select clause are stored.

Parameters

Cake\Database\TypeMap $typeMap
The map object to use

Returns


$this

traverse()source public

traverse( callable $visitor , array $parts [] )

Will iterate over every specified part. Traversing functions can aggregate results using variables in the closure or instance variables. This function is commonly used as a way for traversing all query parts that are going to be used for constructing a query.

The callback will receive 2 parameters, the first one is the value of the query part that is being iterated and the second the name of such part.

Example:

$query->select(['title'])->from('articles')->traverse(function ($value, $clause) {
    if ($clause === 'select') {
        var_dump($value);
    }
}, ['select', 'from']);

Parameters

callable $visitor
A function or callable to be executed for each part
array $parts optional []
The query clauses to traverse

Returns


$this

Implementation of

Cake\Database\ExpressionInterface::traverse()

traverseExpressions()source public

traverseExpressions( callable $callback )

This function works similar to the traverse() function, with the difference that it does a full depth traversal of the entire expression tree. This will execute the provided callback function for each ExpressionInterface object that is stored inside this query at any nesting depth in any part of the query.

Callback will receive as first parameter the currently visited expression.

Parameters

callable $callback

the function to be executed for each ExpressionInterface found inside this query.

Returns


$this|null

type()source public

type( )

Returns the type of this query (select, insert, update, delete)

Returns

string

union()source public

union( string|Cake\Database\Query $query , boolean $overwrite false )

Adds a complete query to be used in conjunction with an UNION operator with this query. This is used to combine the result set of this query with the one that will be returned by the passed query. You can add as many queries as you required by calling multiple times this method with different queries.

By default, the UNION operator will remove duplicate rows, if you wish to include every row for all queries, use unionAll().

Examples

$union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
$query->select(['id', 'name'])->from(['d' => 'things'])->union($union);

Will produce:

SELECT id, name FROM things d UNION SELECT id, title FROM articles a

Parameters

string|Cake\Database\Query $query
full SQL query to be used in UNION operator
boolean $overwrite optional false
whether to reset the list of queries to be operated or not

Returns


$this

unionAll()source public

unionAll( string|Cake\Database\Query $query , boolean $overwrite false )

Adds a complete query to be used in conjunction with the UNION ALL operator with this query. This is used to combine the result set of this query with the one that will be returned by the passed query. You can add as many queries as you required by calling multiple times this method with different queries.

Unlike UNION, UNION ALL will not remove duplicate rows.

$union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
$query->select(['id', 'name'])->from(['d' => 'things'])->unionAll($union);

Will produce:

SELECT id, name FROM things d UNION ALL SELECT id, title FROM articles a

Parameters

string|Cake\Database\Query $query
full SQL query to be used in UNION operator
boolean $overwrite optional false
whether to reset the list of queries to be operated or not

Returns


$this

valueBinder()source public

valueBinder( Cake\Database\ValueBinder|null $binder null )

Returns the currently used ValueBinder instance. If a value is passed, it will be set as the new instance to be used.

A ValueBinder is responsible for generating query placeholders and temporarily associate values to those placeholders so that they can be passed correctly statement object.

Parameters

Cake\Database\ValueBinder|null $binder optional null

new instance to be set. If no value is passed the default one will be returned

Returns


$this|\Cake\Database\ValueBinder

values()source public

values( array|Cake\Database\Query $data )

Set the values for an insert query.

Multi inserts can be performed by calling values() more than one time, or by providing an array of value sets. Additionally $data can be a Query instance to insert data from another SELECT statement.

Parameters

array|Cake\Database\Query $data
The data to insert.

Returns


$this

Throws

Cake\Database\Exception

if you try to set values before declaring columns. Or if you try to set values on non-insert queries.


where()source public

where( string|array|Cake\Database\ExpressionInterface|callable|null $conditions null , array $types [] , boolean $overwrite false )

Adds a condition or set of conditions to be used in the WHERE clause for this query. Conditions can be expressed as an array of fields as keys with comparison operators in it, the values for the array will be used for comparing the field to such literal. Finally, conditions can be expressed as a single string or an array of strings.

When using arrays, each entry will be joined to the rest of the conditions using an AND operator. Consecutive calls to this function will also join the new conditions specified using the AND operator. Additionally, values can be expressed using expression objects which can include other query objects.

Any conditions created with this methods can be used with any SELECT, UPDATE and DELETE type of queries.

Conditions using operators:

$query->where([
    'posted >=' => new DateTime('3 days ago'),
    'title LIKE' => 'Hello W%',
    'author_id' => 1,
], ['posted' => 'datetime']);

The previous example produces:

WHERE posted >= 2012-01-27 AND title LIKE 'Hello W%' AND author_id = 1

Second parameter is used to specify what type is expected for each passed key. Valid types can be used from the mapped with Database\Type class.

Nesting conditions with conjunctions:

$query->where([
    'author_id !=' => 1,
    'OR' => ['published' => true, 'posted <' => new DateTime('now')],
    'NOT' => ['title' => 'Hello']
], ['published' => boolean, 'posted' => 'datetime']

The previous example produces:

WHERE author_id = 1 AND (published = 1 OR posted < '2012-02-01') AND NOT (title = 'Hello')

You can nest conditions using conjunctions as much as you like. Sometimes, you may want to define 2 different options for the same key, in that case, you can wrap each condition inside a new array:

$query->where(['OR' => [['published' => false], ['published' => true]])

Keep in mind that every time you call where() with the third param set to false (default), it will join the passed conditions to the previous stored list using the AND operator. Also, using the same array key twice in consecutive calls to this method will not override the previous value.

Using expressions objects:

$exp = $query->newExpr()->add(['id !=' => 100, 'author_id' != 1])->tieWith('OR');
$query->where(['published' => true], ['published' => 'boolean'])->where($exp);

The previous example produces:

WHERE (id != 100 OR author_id != 1) AND published = 1

Other Query objects that be used as conditions for any field.

Adding conditions in multiple steps:

You can use callable functions to construct complex expressions, functions receive as first argument a new QueryExpression object and this query instance as second argument. Functions must return an expression object, that will be added the list of conditions for the query using the AND operator.

$query
  ->where(['title !=' => 'Hello World'])
  ->where(function ($exp, $query) {
    $or = $exp->or_(['id' => 1]);
    $and = $exp->and_(['id >' => 2, 'id <' => 10]);
   return $or->add($and);
  });
  • The previous example produces:

WHERE title != 'Hello World' AND (id = 1 OR (id > 2 AND id < 10))

Conditions as strings:

$query->where(['articles.author_id = authors.id', 'modified IS NULL']);

The previous example produces:

WHERE articles.author_id = authors.id AND modified IS NULL

Please note that when using the array notation or the expression objects, all values will be correctly quoted and transformed to the correspondent database data type automatically for you, thus securing your application from SQL injections. If you use string conditions make sure that your values are correctly quoted. The safest thing you can do is to never use string conditions.

Parameters

string|array|Cake\Database\ExpressionInterface|callable|null $conditions optional null
The conditions to filter on.
array $types optional []
associative array of type names used to bind values to query
boolean $overwrite optional false
whether to reset conditions with passed list or not

Returns


$this

See

Cake\Database\Type
Cake\Database\Expression\QueryExpression

Methods used from Cake\Datasource\QueryTrait

_decoratorClass()source protected

_decoratorClass( )

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

Returns

string

aliasField()source 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()source 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

eagerLoaded()source public

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.

Parameters

boolean|null $value optional null
Whether or not to eager load.

Returns


$this|\Cake\ORM\Query

first()source 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

mixed
the first result from the ResultSet

firstOrFail()source public

firstOrFail( )

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

Returns

mixed
The first result from the ResultSet.

Throws

Cake\Datasource\Exception\RecordNotFoundException
When there is no first record.

formatResults()source 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, a ResultSetDecorator, 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 map reduce routines.

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

getOptions()source 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\ORM\Query::applyOptions() to read about the options that will be processed by this class and not returned by this function


mapReduce()source 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.

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

toArray( )

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

Returns

array

Methods used from Cake\Database\TypeMapTrait

defaultTypes()source public

defaultTypes( array $types null )

Allows setting default types when chaining query

Deprecated

3.4.0 Use setDefaultTypes()/getDefaultTypes() instead.

Parameters

array $types optional null
The array of types to set.

Returns


$this|array

getDefaultTypes()source public

getDefaultTypes( )

Gets default types of current type map.

Returns

array

getTypeMap()source public

getTypeMap( )

Returns the existing type map.

Returns

Cake\Database\TypeMap

setDefaultTypes()source public

setDefaultTypes( array $types )

Allows setting default types when chaining query.

Parameters

array $types
The array of types to set.

Returns


$this

setTypeMap()source public

setTypeMap( array|Cake\Database\TypeMap $typeMap )

Creates a new TypeMap if $typeMap is an array, otherwise exchanges it for the given one.

Parameters

array|Cake\Database\TypeMap $typeMap
Creates a TypeMap if array, otherwise sets the given TypeMap

Returns


$this

typeMap()source public

typeMap( array|Cake\Database\TypeMap|null $typeMap null )

Creates a new TypeMap if $typeMap is an array, otherwise returns the existing type map or exchanges it for the given one.

Deprecated

3.4.0 Use setTypeMap()/getTypeMap() instead.

Parameters

array|Cake\Database\TypeMap|null $typeMap optional null
Creates a TypeMap if array, otherwise sets the given TypeMap

Returns


$this|\Cake\Database\TypeMap

Magic methods summary

append()source public

append( array|Traversable $items )

Appends more rows to the result of the query.

Parameters

array|Traversable $items

Returns

Cake\Collection\CollectionInterface

chunk()source public

chunk( $size )

Groups the results in arrays of $size rows each.

Parameters

$size

Returns

Cake\Collection\CollectionInterface

combine()source public

combine( $k , $v , $g )

Returns the values of the column $v index by column $k, and grouped by $g.

Parameters

$k
$v
$g optional

Returns

Cake\Collection\CollectionInterface

countBy()source public

countBy( string|callable $field )

Returns the number of unique values for a column

Parameters

string|callable $field

Returns

integer

each()source public

each( callable $c )

Passes each of the query results to the callable

Parameters

callable $c

Returns

Cake\Collection\CollectionInterface

every()source public

every( callable $c )

Returns true if all the results pass the callable test

Parameters

callable $c

Returns

boolean

extract()source public

extract( $field )

Extracts a single column from each row

Parameters

$field

Returns

Cake\Collection\CollectionInterface

filter()source public

filter( callable $c )

Keeps the results using passing the callable test

Parameters

callable $c optional

Returns

Cake\Collection\CollectionInterface

groupBy()source public

groupBy( string|callable $field )

In-memory group all results by the value of a column.

Parameters

string|callable $field

Returns

Cake\Collection\CollectionInterface

indexBy()source public

indexBy( string|callable $field )

Returns the results indexed by the value of a column.

Parameters

string|callable $field

Returns

Cake\Collection\CollectionInterface

isEmpty()source public

isEmpty( )

Returns true if this query found no results.

Returns

boolean

last()source public

last( )

Return the last row of the query result

Returns

mixed

map()source public

map( callable $c )

Modifies each of the results using the callable

Parameters

callable $c

Returns

Cake\Collection\CollectionInterface

max()source public

max( $field , $type )

Returns the maximum value for a single column in all the results.

Parameters

$field
$type optional

Returns

mixed

min()source public

min( $field , $type )

Returns the minimum value for a single column in all the results.

Parameters

$field
$type optional

Returns

mixed

nest()source public

nest( $k , $p , $n )

Creates a tree structure by nesting the values of column $p into that with the same value for $k using $n as the nesting key.

Parameters

$k
$p
$n optional

Returns

Cake\Collection\CollectionInterface

reduce()source public

reduce( callable $c , $zero )

Folds all the results into a single value using the callable.

Parameters

callable $c
$zero optional

Returns

mixed

reject()source public

reject( callable $c )

Removes the results passing the callable test

Parameters

callable $c

Returns

Cake\Collection\CollectionInterface

sample()source public

sample( $size )

In-memory shuffle the results and return a subset of them.

Parameters

$size optional

Returns

Cake\Collection\CollectionInterface

shuffle()source public

shuffle( )

In-memory randomize the order the results are returned

Returns

Cake\Collection\CollectionInterface

skip()source public

skip( integer $howMany )

Skips some rows from the start of the query result.

Parameters

integer $howMany

Returns

Cake\Collection\CollectionInterface

some()source public

some( callable $c )

Returns true if at least one of the results pass the callable test

Parameters

callable $c

Returns

boolean

stopWhen()source public

stopWhen( callable $c )

Returns each row until the callable returns true.

Parameters

callable $c

Returns

Cake\Collection\CollectionInterface

sumOf()source public

sumOf( string|callable $field )

Returns the sum of all values for a single column

Parameters

string|callable $field

Returns

float

take()source public

take( $size , $from )

In-memory limit and offset for the query results.

Parameters

$size optional
$from

Returns

Cake\Collection\CollectionInterface

toArray()source public

toArray( )

Returns a key-value array with the results of this query.

Returns

array

Implementation of

Cake\Datasource\QueryInterface::toArray()

toList()source public

toList( )

Returns a numerically indexed array with the results of this query.

Returns

array

zip()source public

zip( array|Traversable $c )

Returns the first result of both the query and $c in an array, then the second results and so on.

Parameters

array|Traversable $c

Returns

Cake\Collection\CollectionInterface

zipWith()source public

zipWith( $collections , callable $callable )

Returns each of the results out of calling $c with the first rows of the query and each of the items, then the second rows and so on.

Parameters

$collections
callable $callable

Returns

Cake\Collection\CollectionInterface

Properties detail

$_autoFieldssource

protected boolean

Tracks whether or not the original query should include fields from the top level table.

$_beforeFindFiredsource

protected boolean

True if the beforeFind event has already been triggered for this query

false

$_countersource

protected callable

A callable function that can be used to calculate the total amount of records this query will match when not using limit

$_eagerLoadersource

protected Cake\ORM\EagerLoader

Instance of a class responsible for storing association containments and for eager loading them when this query is executed

$_hasFieldssource

protected boolean

Whether the user select any fields before being executed, this is used to determined if any fields should be automatically be selected.

$_hydratesource

protected boolean

Whether to hydrate results into entity objects

true

$_resultsCountsource

protected integer|null

The COUNT(*) for the query.

When set, count query execution will be bypassed.

© 2005–2017 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/3.4/class-Cake.ORM.Query.html