PHP Class Cake\Database\Query

Inheritance: implements Cake\Database\ExpressionInterface, implements IteratorAggregat\IteratorAggregate, use trait Cake\Database\TypeMapTrait
Datei anzeigen Open project: cakephp/cakephp Class Usage Examples

Protected Properties

Property Type Description
$_connection Cake\Datasource\ConnectionInterface Connection instance to be used to execute this query.
$_dirty boolean Indicates whether internal state of this query was changed, this is used to discard internal cached objects such as the transformed query or the reference to the executed statement.
$_functionsBuilder Cake\Database\FunctionsBuilder Instance of functions builder object used for generating arbitrary SQL functions.
$_iterator Cake\Database\StatementInterface Statement object resulting from executing this query.
$_parts array List of SQL parts that will be used to build this query.
$_resultDecorators array A list of callback functions to be called to alter each row from resulting statement upon retrieval. Each one of the callback function will receive the row array as first argument.
$_selectTypeMap Cake\Database\TypeMap The Type map for fields in the select clause
$_type string Type of this query (select, insert, update, delete).
$_typeCastAttached boolean Tracking flag to ensure only one type caster is appended.
$_useBufferedResults boolean Boolean for tracking whether or not buffered results are enabled.
$_valueBinder ValueBinder The object responsible for generating query placeholders and temporarily store values associated to each of those.

Public Methods

Method Description
__clone ( ) : void Do a deep clone on this object.
__construct ( Cake\Datasource\ConnectionInterface $connection ) Constructor.
__debugInfo ( ) : array Returns an array that can be used to describe the internal state of this object.
__toString ( ) : string Returns string representation of this query (complete SQL statement).
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.
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.
bind ( string | integer $param, mixed $value, string | integer $type = 'string' ) Associates a query placeholder to a value and a type.
bufferResults ( boolean | null $enable = null ) : boolean | $this Enable/Disable buffered results.
clause ( string $name ) : mixed 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.
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.
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.
delete ( string | null $table = null ) Create a delete query.
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.
epilog ( string | Cake\Database\Expression\QueryExpression | null $expression = null ) A string or expression that will be appended to the generated query
execute ( ) : Cake\Database\StatementInterface Compiles the SQL representation of this query and executes it using the configured connection object. Returns the resulting statement object.
from ( array | string $tables = [], boolean $overwrite = false ) Adds a single or multiple tables to be used in the FROM clause for this query.
func ( ) : Cake\Database\FunctionsBuilder Returns an instance of a functions builder object that can be used for generating arbitrary SQL functions.
getIterator ( ) : Iterator 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.
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.
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.
innerJoin ( string | array $table, string | array | Cake\Database\ExpressionInterface $conditions = [], array $types = [] ) Adds a single INNER JOIN clause to the query.
insert ( array $columns, array $types = [] ) Create an insert query.
into ( string $table ) Set the table name for insert queries.
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.
leftJoin ( string | array $table, string | array | Cake\Database\ExpressionInterface $conditions = [], array $types = [] ) Adds a single LEFT JOIN clause to the query.
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.
modifier ( array | Cake\Database\ExpressionInterface | string $modifiers, boolean $overwrite = false ) Adds a single or multiple SELECT modifiers to be used in the SELECT.
newExpr ( mixed $rawExpression = null ) : Cake\Database\Expression\QueryExpression 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.
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.
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.
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.
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.
orderAsc ( string | Cake\Database\Expression\QueryExpression $field, boolean $overwrite = false ) Add an ORDER BY clause with an ASC direction.
orderDesc ( string | Cake\Database\Expression\QueryExpression $field, boolean $overwrite = false ) Add an ORDER BY clause with a DESC direction.
page ( integer $num, integer | null $limit = null ) Set the page of results you want.
removeJoin ( string $name ) Remove a join if it has been defined.
rightJoin ( string | array $table, string | array | Cake\Database\ExpressionInterface $conditions = [], array $types = [] ) Adds a single RIGHT JOIN clause to the query.
select ( array | Cake\Database\ExpressionInterface | string | callable $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.
selectTypeMap ( Cake\Database\TypeMap $typeMap = null ) Sets the TypeMap class where the types for each of the fields in the select clause are stored.
set ( string | array | callable | Cake\Database\Expression\QueryExpression $key, mixed $value = null, array $types = [] ) Set one or many fields to update.
sql ( ValueBinder $generator = null ) : string Returns the SQL representation of this object.
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.
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.
type ( ) : string Returns the type of this query (select, insert, update, delete)
union ( string | 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.
unionAll ( string | 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.
update ( string $table ) Create an update query.
valueBinder ( 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.
values ( array | Query $data ) Set the values for an insert query.
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.

Protected Methods

Method Description
_conjugate ( string $part, string | null | array | Cake\Database\ExpressionInterface | callable $append, string $conjunction, array $types ) : void Helper function used to build conditions by composing QueryExpression objects.
_decorateStatement ( Cake\Database\StatementInterface $statement ) : Cake\Database\Statement\CallbackStatement Auxiliary function used to wrap the original statement from the driver with any registered callbacks.
_dirty ( ) : void Marks a query as dirty, removing any preprocessed information from in memory caching.
_makeJoin ( string | array $table, string | array | Cake\Database\ExpressionInterface $conditions, string $type ) : array Returns an array that can be passed to the join method describing a single join clause

Method Details

__clone() public method

Will clone all of the expression objects used in each of the clauses, as well as the valueBinder.
public __clone ( ) : void
return void

__construct() public method

Constructor.
public __construct ( Cake\Datasource\ConnectionInterface $connection )
$connection Cake\Datasource\ConnectionInterface The connection object to be used for transforming and executing this query

__debugInfo() public method

Returns an array that can be used to describe the internal state of this object.
public __debugInfo ( ) : array
return array

__toString() public method

Returns string representation of this query (complete SQL statement).
public __toString ( ) : string
return string

_conjugate() protected method

Helper function used to build conditions by composing QueryExpression objects.
protected _conjugate ( string $part, string | null | array | Cake\Database\ExpressionInterface | callable $append, string $conjunction, array $types ) : void
$part string Name of the query part to append the new part to
$append string | null | array | Cake\Database\ExpressionInterface | callable Expression or builder function to append.
$conjunction string type of conjunction to be used to operate part
$types array associative array of type names used to bind values to query
return void

_decorateStatement() protected method

Auxiliary function used to wrap the original statement from the driver with any registered callbacks.
protected _decorateStatement ( Cake\Database\StatementInterface $statement ) : Cake\Database\Statement\CallbackStatement
$statement Cake\Database\StatementInterface to be decorated
return Cake\Database\Statement\CallbackStatement

_dirty() protected method

Marks a query as dirty, removing any preprocessed information from in memory caching.
protected _dirty ( ) : void
return void

_makeJoin() protected method

Returns an array that can be passed to the join method describing a single join clause
protected _makeJoin ( string | array $table, string | array | Cake\Database\ExpressionInterface $conditions, string $type ) : array
$table string | array The table to join with
$conditions string | array | Cake\Database\ExpressionInterface The conditions to use for joining.
$type string the join type to use
return array

andHaving() public method

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.
See also: Cake\Database\Query::andWhere()
public andHaving ( string | array | Cake\Database\ExpressionInterface | callable $conditions, array $types = [] )
$conditions string | array | Cake\Database\ExpressionInterface | callable The AND conditions for HAVING.
$types array associative array of type names used to bind values to query

andWhere() public method

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)
See also: Cake\Database\Query::where()
See also: Cake\Database\Type
public andWhere ( string | array | Cake\Database\ExpressionInterface | callable $conditions, array $types = [] )
$conditions string | array | Cake\Database\ExpressionInterface | callable The conditions to add with AND.
$types array associative array of type names used to bind values to query

bind() public method

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.
public bind ( string | integer $param, mixed $value, string | integer $type = 'string' )
$param string | integer placeholder to be replaced with quoted version of $value
$value mixed The value to be bound
$type string | integer the mapped type name, used for casting when sending to database

bufferResults() public method

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.
public bufferResults ( boolean | null $enable = null ) : boolean | $this
$enable boolean | null whether or not to enable buffering
return boolean | $this

clause() public method

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
public clause ( string $name ) : mixed
$name string name of the clause to be returned
return mixed

connection() public method

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.
public connection ( Cake\Datasource\ConnectionInterface | null $connection = null )
$connection Cake\Datasource\ConnectionInterface | null instance

decorateResults() public method

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; });
public decorateResults ( callable | null $callback, boolean $overwrite = false )
$callback callable | null The callback to invoke when results are fetched.
$overwrite boolean Whether or not this should append or replace all existing decorators.

delete() public method

Can be combined with from(), where() and other methods to create delete queries with specific conditions.
public delete ( string | null $table = null )
$table string | null The table to use when deleting.

distinct() public method

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);
public distinct ( array | Cake\Database\ExpressionInterface | string | boolean $on = [], boolean $overwrite = false )
$on array | Cake\Database\ExpressionInterface | string | boolean Enable/disable distinct class or list of fields to be filtered on
$overwrite boolean whether to reset fields with passed list or not

epilog() public method

### Examples: $query->select('id')->where(['author_id' => 1])->epilog('FOR UPDATE'); $query ->insert('articles', ['title']) ->values(['author_id' => 1]) ->epilog('RETURNING id');
public epilog ( string | Cake\Database\Expression\QueryExpression | null $expression = null )
$expression string | Cake\Database\Expression\QueryExpression | null The expression to be appended

execute() public method

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.
public execute ( ) : Cake\Database\StatementInterface
return Cake\Database\StatementInterface

from() public method

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
public from ( array | string $tables = [], boolean $overwrite = false )
$tables array | string 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.
$overwrite boolean whether to reset tables with passed list or not

func() public method

### Example: $query->func()->count('*'); $query->func()->dateDiff(['2012-01-05', '2012-01-02'])
public func ( ) : Cake\Database\FunctionsBuilder
return Cake\Database\FunctionsBuilder

getIterator() public method

Executes this query and returns a results iterator. This function is required for implementing the IteratorAggregate interface and allows the query to be iterated without having to call execute() manually, thus making it look like a result set instead of the query itself.
public getIterator ( ) : Iterator
return Iterator

group() public method

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');
public group ( array | Cake\Database\ExpressionInterface | string $fields, boolean $overwrite = false )
$fields array | Cake\Database\ExpressionInterface | string fields to be added to the list
$overwrite boolean whether to reset fields with passed list or not

having() public method

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.
See also: Cake\Database\Query::where()
public having ( string | array | Cake\Database\ExpressionInterface | callable | null $conditions = null, array $types = [], boolean $overwrite = false )
$conditions string | array | Cake\Database\ExpressionInterface | callable | null The having conditions.
$types array associative array of type names used to bind values to query
$overwrite boolean whether to reset conditions with passed list or not

innerJoin() public method

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.
public innerJoin ( string | array $table, string | array | Cake\Database\ExpressionInterface $conditions = [], array $types = [] )
$table string | array The table to join with
$conditions string | array | Cake\Database\ExpressionInterface The conditions to use for joining.
$types array a list of types associated to the conditions used for converting values to the corresponding database representation.

insert() public method

Note calling this method will reset any data previously set with Query::values().
public insert ( array $columns, array $types = [] )
$columns array The columns to insert into.
$types array A map between columns & their datatypes.

into() public method

Set the table name for insert queries.
public into ( string $table )
$table string The table name to insert into.

join() public method

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 produce INNER 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
See also: Cake\Database\Type
public join ( array | string | null $tables = null, array $types = [], boolean $overwrite = false )
$tables array | string | null list of tables to be joined in the query
$types array associative array of type names used to bind values to query
$overwrite boolean whether to reset joins with passed list or not

leftJoin() public method

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.
public leftJoin ( string | array $table, string | array | Cake\Database\ExpressionInterface $conditions = [], array $types = [] )
$table string | array The table to join with
$conditions string | array | Cake\Database\ExpressionInterface The conditions to use for joining.
$types array a list of types associated to the conditions used for converting values to the corresponding database representation.

limit() public method

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)
public limit ( integer | Cake\Database\ExpressionInterface $num )
$num integer | Cake\Database\ExpressionInterface number of records to be returned

modifier() public method

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
public modifier ( array | Cake\Database\ExpressionInterface | string $modifiers, boolean $overwrite = false )
$modifiers array | Cake\Database\ExpressionInterface | string modifiers to be applied to the query
$overwrite boolean whether to reset order with field list or not

newExpr() public method

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
public newExpr ( mixed $rawExpression = null ) : Cake\Database\Expression\QueryExpression
$rawExpression mixed A string, array or anything you want wrapped in an expression object
return Cake\Database\Expression\QueryExpression

offset() public method

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)
public offset ( integer | Cake\Database\ExpressionInterface $num )
$num integer | Cake\Database\ExpressionInterface number of records to be skipped

orHaving() public method

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.
See also: Cake\Database\Query::orWhere()
public orHaving ( string | array | Cake\Database\ExpressionInterface | callable $conditions, array $types = [] )
$conditions string | array | Cake\Database\ExpressionInterface | callable The OR conditions for HAVING.
$types array associative array of type names used to bind values to query.

orWhere() public method

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)
See also: Cake\Database\Query::where()
See also: Cake\Database\Type
public orWhere ( string | array | Cake\Database\ExpressionInterface | callable $conditions, array $types = [] )
$conditions string | array | Cake\Database\ExpressionInterface | callable The conditions to add with OR.
$types array associative array of type names used to bind values to query

order() public method

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().
public order ( array | Cake\Database\ExpressionInterface | string $fields, boolean $overwrite = false )
$fields array | Cake\Database\ExpressionInterface | string fields to be added to the list
$overwrite boolean whether to reset order with field list or not

orderAsc() public method

This method allows you to set complex expressions as order conditions unlike order()
public orderAsc ( string | Cake\Database\Expression\QueryExpression $field, boolean $overwrite = false )
$field string | Cake\Database\Expression\QueryExpression The field to order on.
$overwrite boolean Whether or not to reset the order clauses.

orderDesc() public method

This method allows you to set complex expressions as order conditions unlike order()
public orderDesc ( string | Cake\Database\Expression\QueryExpression $field, boolean $overwrite = false )
$field string | Cake\Database\Expression\QueryExpression The field to order on.
$overwrite boolean Whether or not to reset the order clauses.

page() public method

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.
public page ( integer $num, integer | null $limit = null )
$num integer The page number you want.
$limit integer | null The number of rows you want in the page. If null the current limit clause will be used.

removeJoin() public method

Useful when you are redefining joins or want to re-order the join clauses.
public removeJoin ( string $name )
$name string The alias/name of the join to remove.

rightJoin() public method

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.
public rightJoin ( string | array $table, string | array | Cake\Database\ExpressionInterface $conditions = [], array $types = [] )
$table string | array The table to join with
$conditions string | array | Cake\Database\ExpressionInterface The conditions to use for joining.
$types array a list of types associated to the conditions used for converting values to the corresponding database representation.

select() public method

If an array is passed, keys will be used to alias fields using the value as the real field to be aliased. It is possible to alias strings, Expression objects or even other Query objects. If a callable function is passed, the returning array of the function will be used as the list of fields. 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->select(['id', 'title']); // Produces SELECT id, title $query->select(['author' => 'author_id']); // Appends author: SELECT id, title, author_id as author $query->select('id', true); // Resets the list: SELECT id $query->select(['total' => $countQuery]); // SELECT id, (SELECT ...) AS total $query->select(function ($query) { return ['article_id', 'total' => $query->count('*')]; }) By default no fields are selected, if you have an instance of Cake\ORM\Query and try to append fields you should also call Cake\ORM\Query::autoFields() to select the default fields from the table.
public select ( array | Cake\Database\ExpressionInterface | string | callable $fields = [], boolean $overwrite = false )
$fields array | Cake\Database\ExpressionInterface | string | callable fields to be added to the list.
$overwrite boolean whether to reset fields with passed list or not

selectTypeMap() public method

When called with no arguments, the current TypeMap object is returned.
public selectTypeMap ( Cake\Database\TypeMap $typeMap = null )
$typeMap Cake\Database\TypeMap The map object to use

set() public method

### 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'); });
public set ( string | array | callable | Cake\Database\Expression\QueryExpression $key, mixed $value = null, array $types = [] )
$key string | array | callable | Cake\Database\Expression\QueryExpression 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.
$value mixed 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.
$types array The column types to treat data as.

sql() public method

This function will compile this query to make it compatible with the SQL dialect that is used by the connection, This process might add, remove or alter any query part or internal expression to make it executable in the target platform. The resulting query may have placeholders that will be replaced with the actual values when the query is executed, hence it is most suitable to use with prepared statements.
public sql ( ValueBinder $generator = null ) : string
$generator ValueBinder A placeholder object that will hold associated values for expressions
return string

traverse() public method

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']);
public traverse ( callable $visitor, array $parts = [] )
$visitor callable A function or callable to be executed for each part
$parts array The query clauses to traverse

traverseExpressions() public method

Callback will receive as first parameter the currently visited expression.
public traverseExpressions ( callable $callback )
$callback callable the function to be executed for each ExpressionInterface found inside this query.

type() public method

Returns the type of this query (select, insert, update, delete)
public type ( ) : string
return string

union() public method

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
public union ( string | Query $query, boolean $overwrite = false )
$query string | Query full SQL query to be used in UNION operator
$overwrite boolean whether to reset the list of queries to be operated or not

unionAll() public method

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
public unionAll ( string | Query $query, boolean $overwrite = false )
$query string | Query full SQL query to be used in UNION operator
$overwrite boolean whether to reset the list of queries to be operated or not

update() public method

Can be combined with set() and where() methods to create update queries.
public update ( string $table )
$table string The table you want to update.

valueBinder() public method

A ValueBinder is responsible for generating query placeholders and temporarily associate values to those placeholders so that they can be passed correctly statement object.
public valueBinder ( ValueBinder | null $binder = null )
$binder ValueBinder | null new instance to be set. If no value is passed the default one will be returned

values() public method

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.
public values ( array | Query $data )
$data array | Query The data to insert.

where() public method

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.
See also: Cake\Database\Type
See also: Cake\Database\Expression\QueryExpression
public where ( string | array | Cake\Database\ExpressionInterface | callable | null $conditions = null, array $types = [], boolean $overwrite = false )
$conditions string | array | Cake\Database\ExpressionInterface | callable | null The conditions to filter on.
$types array associative array of type names used to bind values to query
$overwrite boolean whether to reset conditions with passed list or not

Property Details

$_connection protected_oe property

Connection instance to be used to execute this query.
protected ConnectionInterface,Cake\Datasource $_connection
return Cake\Datasource\ConnectionInterface

$_dirty protected_oe property

Indicates whether internal state of this query was changed, this is used to discard internal cached objects such as the transformed query or the reference to the executed statement.
protected bool $_dirty
return boolean

$_functionsBuilder protected_oe property

Instance of functions builder object used for generating arbitrary SQL functions.
protected FunctionsBuilder,Cake\Database $_functionsBuilder
return Cake\Database\FunctionsBuilder

$_iterator protected_oe property

Statement object resulting from executing this query.
protected StatementInterface,Cake\Database $_iterator
return Cake\Database\StatementInterface

$_parts protected_oe property

List of SQL parts that will be used to build this query.
protected array $_parts
return array

$_resultDecorators protected_oe property

A list of callback functions to be called to alter each row from resulting statement upon retrieval. Each one of the callback function will receive the row array as first argument.
protected array $_resultDecorators
return array

$_selectTypeMap protected_oe property

The Type map for fields in the select clause
protected TypeMap,Cake\Database $_selectTypeMap
return Cake\Database\TypeMap

$_type protected_oe property

Type of this query (select, insert, update, delete).
protected string $_type
return string

$_typeCastAttached protected_oe property

Tracking flag to ensure only one type caster is appended.
protected bool $_typeCastAttached
return boolean

$_useBufferedResults protected_oe property

Boolean for tracking whether or not buffered results are enabled.
protected bool $_useBufferedResults
return boolean

$_valueBinder protected_oe property

The object responsible for generating query placeholders and temporarily store values associated to each of those.
protected ValueBinder,Cake\Database $_valueBinder
return ValueBinder