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.
int
0
Indicates that the operation should append to the list
string
'INNER'
string
'LEFT'
string
'RIGHT'
bool
true
Indicates that the operation should overwrite the list
int
1
Indicates that the operation should prepend to the list
bool|null
Tracks whether the original query should include fields from the top level table.
bool
True if the beforeFind event has already been triggered for this query
Cake\Datasource\QueryCacher|null
A query cacher instance if this query has caching enabled.
Cake\Database\Connection
Connection instance to be used to execute this query.
callable|null
A callable function that can be used to calculate the total amount of records this query will match when not using limit
array<string>
The list of query clauses to traverse for generating a DELETE statement
bool
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.
bool
Whether the query is standalone or the product of an eager load operation.
Cake\ORM\EagerLoader|null
Instance of a class responsible for storing association containments and for eager loading them when this query is executed
array<callable>
List of formatter classes or callbacks that will post-process the results when fetched
Cake\Database\FunctionsBuilder|null
Instance of functions builder object used for generating arbitrary SQL functions.
bool|null
Whether the user select any fields before being executed, this is used to determined if any fields should be automatically be selected.
bool
Whether to hydrate results into entity objects
array<string>
The list of query clauses to traverse for generating an INSERT statement
Cake\Database\StatementInterface|null
Statement object resulting from executing this query.
array
List of map-reduce routines that should be applied over the query result
array
Holds any custom options passed using applyOptions that could not be processed by any method in this class.
array<string, mixed>
List of SQL parts that will be used to build this query.
Cake\ORM\Table
Instance of a table object this query is bound to.
array<callable>
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.
iterable|null
A ResultSet.
int|null
The COUNT(*) for the query.
array<string>
The list of query clauses to traverse for generating a SELECT statement
Cake\Database\TypeMap|null
The Type map for fields in the select clause
string
Type of this query (select, insert, update, delete).
Cake\Database\TypeMap|null
array<string>
The list of query clauses to traverse for generating an UPDATE statement
bool
Boolean for tracking whether buffered results are enabled.
Cake\Database\ValueBinder|null
The object responsible for generating query placeholders and temporarily store values associated to each of those.
bool
Whether aliases are generated for fields.
bool
Tracking flag to disable casting
Enables calling methods from the result set as if they were from this class
Handles clearing iterator and cloning all expressions and value binders.
Constructor
Returns an array that can be used to describe the internal state of this object.
Returns string representation of this query (complete SQL statement).
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
Helper function used to build conditions by composing QueryExpression objects.
Decorates the results iterator with MapReduce routines and formatters
Auxiliary function used to wrap the original statement from the driver with any registered callbacks.
Returns the name of the class to be used for decorating results
Marks a query as dirty, removing any preprocessed information from in memory caching such as previous results
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.
Query parts traversal method used by traverseExpressions()
Returns an array that can be passed to the join method describing a single join clause
Performs and returns the COUNT(*) for the query.
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 themselves when specifying conditions.
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.
Runs aliasField()
for each field in the provided list and returns the result under a single array.
Fetch the results for this query.
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.
Connects any previously defined set of conditions to the provided list using the AND operator. {@see \Cake\Database\Query::andWhere()}
Appends more rows to the result of the query.
Populates or adds parts to current query clauses using an array. This is handy for passing all query clauses at once.
Associates a query placeholder to a value and a type.
Enable result caching for this query.
Groups the results in arrays of $size rows each.
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.
Creates a copy of this current query, triggers beforeFind and resets some state.
Clears the contained associations from the current query.
Clears the internal result cache and the internal count value from the current query object.
Returns the values of the column $v index by column $k, and grouped by $g.
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.
Returns the total amount of results for the query.
Returns the number of unique values for a column
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.
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.
Create a delete query.
Disables automatically appending fields.
Disables buffered results.
Disable hydrating entities.
Disables result casting.
Adds a DISTINCT
clause to the query to remove duplicates from the result set. This clause can only be used for select statements.
Passes each of the query results to the callable
Sets the query instance to be an eager loaded query. If no argument is passed, the current configured query _eagerLoaded
value is returned.
Sets whether the ORM should automatically append fields.
Enables/Disables buffered results.
Toggle hydrating entities.
Enables result casting.
A string or expression that will be appended to the generated query
Returns true if all the results pass the callable test
Compiles the SQL representation of this query and executes it using the configured connection object. Returns the resulting statement object.
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.
Extracts a single column from each row
Keeps the results using passing the callable test
Apply custom finds to against an existing query object.
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.
Get the first result from the executing query or raise an exception.
Registers a new formatter callback function that is to be executed when trying to fetch the results from the database.
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.
Returns an instance of a functions builder object that can be used for generating arbitrary SQL functions.
Gets the connection instance to be used for executing and transforming this query.
Gets default types of current type map.
Returns the currently configured instance.
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 the list of previously registered map reduce routines.
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.
Returns the default table object that will be used by this query, that is, the table that will appear in the from clause.
Returns the list of previously registered format routines.
Gets the TypeMap class where the types for each of the fields in the select clause are stored.
Returns the existing type map.
Returns the currently used ValueBinder instance.
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.
In-memory group all results by the value of a column.
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.
Creates an expression that refers to an identifier. Identifiers are used to refer to field names and allow the SQL compiler to apply quotes or escape the identifier.
Returns the results indexed by the value of a column.
Adds a single INNER JOIN
clause to the query.
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.
Create an insert query.
Set the table name for insert queries.
Gets whether the ORM should automatically append fields.
Returns whether buffered results are enabled/disabled.
Returns the current configured query _eagerLoaded
value
Returns true if this query found no results.
Returns the current hydration mode.
Returns whether result casting is enabled/disabled.
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.
Executes the query and converts the result set into JSON.
Return the last row of the query result
Adds a single LEFT JOIN
clause to the query.
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.
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.
Modifies each of the results using the callable
Register a new MapReduce routine to be executed on top of the database results Both the mapper and caller callable should be invokable objects.
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.
Returns the maximum value for a single column in all the results.
Returns the minimum value for a single column in all the results.
Adds a single or multiple SELECT
modifiers to be used in the SELECT
.
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.
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.
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.
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.
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.
Add an ORDER BY clause with an ASC direction.
Add an ORDER BY clause with a DESC direction.
Set the page of results you want.
Folds all the results into a single value using the callable.
Removes the results passing the callable test
Remove a join if it has been defined.
Set the default Table object that will be used by this query and form the FROM
clause.
Adds a single RIGHT JOIN
clause to the query.
Executes the SQL of this query and immediately closes the statement before returning the row count of records changed.
In-memory shuffle the results and return a subset of them.
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.
All the fields associated with the passed table except the excluded fields will be added to the select clause of the query. Passed excluded fields should not be aliased. After the first call to this method, a second call cannot be used to remove fields that have already been added to the query by the first. If you need to change the list after the first call, pass overwrite boolean true which will reset the select clause removing all previous additions.
Set one or many fields to update.
Sets the connection instance to be used for executing and transforming this query.
Overwrite the default type mappings for fields in the implementing object.
Sets the instance of the eager loader class to use for loading associations and storing containments.
Set the result set for a query.
Sets the TypeMap class where the types for each of the fields in the select clause are stored.
Creates a new TypeMap if $typeMap is an array, otherwise exchanges it for the given one.
Overwrite the current value binder
In-memory randomize the order the results are returned
Skips some rows from the start of the query result.
Returns true if at least one of the results pass the callable test
Sorts the query with the callback
Returns the SQL representation of this object.
Returns each row until the callable returns true.
Returns a new Query that has automatic field aliasing disabled.
Returns the sum of all values for a single column
In-memory limit and offset for the query results.
Returns a key-value array with the results of this query.
Returns a numerically indexed array with the results of this query.
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.
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.
Will iterate over the provided parts.
Trigger the beforeFind event on the query's repository object.
Returns the type of this query (select, insert, update, delete)
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.
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.
Create an update query.
Set the values for an insert query.
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.
Adds an IN condition or set of conditions to be used in the WHERE clause for this query.
Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query.
Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query. This also allows the field to be null with a IS NULL condition since the null value would cause the NOT IN condition to always fail.
Convenience method that adds a NOT NULL condition to the query
Convenience method that adds a IS NULL condition to the query
Adds a named window expression.
Adds a new common table expression (CTE) to the query.
Returns the first result of both the query and $c in an array, then the second results and so on.
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.
__call(string $method, array $arguments): mixed
Enables calling methods from the result set as if they were from this class
string
$method the method to call
array
$arguments list of arguments for the method to call
mixed
BadMethodCallException
__clone(): void
Handles clearing iterator and cloning all expressions and value binders.
Handles cloning eager loaders.
void
__construct(Cake\Database\Connection $connection, Cake\ORM\Table $table)
Constructor
Cake\Database\Connection
$connection The connection object
Cake\ORM\Table
$table The table this query is starting on
__debugInfo(): array<string, mixed>
Returns an array that can be used to describe the internal state of this object.
array<string, mixed>
__toString(): string
Returns string representation of this query (complete SQL statement).
string
_addAssociationsToTypeMap(Cake\ORM\Table $table, Cake\Database\TypeMap $typeMap, array<string, array> $associations): void
Used to recursively add contained association column types to the query.
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 {@link \Cake\ORM\Query::addDefaultTypes()}
array<string, array>
$associations The nested tree of associations to walk.
void
_addDefaultFields(): void
Inspects if there are any set fields for selecting, otherwise adds all the fields for the default table.
void
_addDefaultSelectTypes(): void
Sets the default types for converting the fields in the select clause
void
_conjugate(string $part, Cake\Database\ExpressionInterfaceClosure|array|string|null $append, string $conjunction, array<string, string> $types): void
Helper function used to build conditions by composing QueryExpression objects.
string
$part Name of the query part to append the new part to
Cake\Database\ExpressionInterfaceClosure|array|string|null
$append Expression or builder function to append. to append.
string
$conjunction type of conjunction to be used to operate part
array<string, string>
$types Associative array of type names used to bind values to query
void
_decorateResults(Traversable $result): Cake\Datasource\ResultSetInterface
Decorates the results iterator with MapReduce routines and formatters
Traversable
$result Original results
Cake\Datasource\ResultSetInterface
_decorateStatement(Cake\Database\StatementInterface $statement): Cake\Database\Statement\CallbackStatementCake\Database\StatementInterface
Auxiliary function used to wrap the original statement from the driver with any registered callbacks.
Cake\Database\StatementInterface
$statement to be decorated
Cake\Database\Statement\CallbackStatementCake\Database\StatementInterface
_decoratorClass(): string
Returns the name of the class to be used for decorating results
string
_dirty(): void
Marks a query as dirty, removing any preprocessed information from in memory caching such as previous results
void
_execute(): Cake\Datasource\ResultSetInterface
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.
Cake\Datasource\ResultSetInterface
_expressionsVisitor(Cake\Database\ExpressionInterface|arrayCake\Database\ExpressionInterface> $expression, Closure $callback): void
Query parts traversal method used by traverseExpressions()
Cake\Database\ExpressionInterface|arrayCake\Database\ExpressionInterface>
$expression Query expression or array of expressions.
Closure
$callback The callback to be executed for each ExpressionInterface found inside this query.
void
_makeJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions, string $type): array
Returns an array that can be passed to the join method describing a single join clause
array<string, mixed>|string
$table The table to join with
Cake\Database\ExpressionInterface|array|string
$conditions The conditions to use for joining.
string
$type the join type to use
array
_performCount(): int
Performs and returns the COUNT(*) for the query.
int
_transformQuery(): void
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
void
addDefaultTypes(Cake\ORM\Table $table): $this
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 themselves when specifying conditions.
This method returns the same query object for chaining.
Cake\ORM\Table
$table The table to pull types from
$this
aliasField(string $field, string|null $alias = null): array<string, string>
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.
string
$field The field to alias
string|null
$alias optional the alias used to prefix the field
array<string, string>
aliasFields(array $fields, string|null $defaultAlias = null): array<string, string>
Runs aliasField()
for each field in the provided list and returns the result under a single array.
array
$fields The fields to alias
string|null
$defaultAlias optional The default alias
array<string, string>
all(): Cake\Datasource\ResultSetInterface
Fetch the results for this query.
Will return either the results set through setResult(), or execute this query and return the ResultSetDecorator object ready for streaming of results.
ResultSetDecorator is a traversable object that implements the methods found on Cake\Collection\Collection.
Cake\Datasource\ResultSetInterface
RuntimeException
andHaving(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): $this
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.
Having fields are not suitable for use with user supplied data as they are not sanitized by the query builder.
Cake\Database\ExpressionInterfaceClosure|array|string
$conditions The AND conditions for HAVING.
array<string, string>
$types optional Associative array of type names used to bind values to query
$this
andWhere(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array $types = []): $this
Connects any previously defined set of conditions to the provided list using the AND operator. {@see \Cake\Database\Query::andWhere()}
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.
$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 ->or(['author_id' => 1]) ->add(['author_id' => 2]); });
Generates the following conditions:
WHERE (title = 'Foo') AND (author_id = 1 OR author_id = 2)
Cake\Database\ExpressionInterfaceClosure|array|string
$conditions array
$types optional $this
append(arrayTraversable $items): Cake\Collection\CollectionInterface
Appends more rows to the result of the query.
arrayTraversable
$items Cake\Collection\CollectionInterface
applyOptions(array<string, mixed> $options): $this
Populates or adds parts to current query clauses using an array. This is handy for passing all query clauses at once.
The method accepts the following query clause related options:
All other options will not affect the query, but will be stored as custom options that can be read via getOptions()
. Furthermore they are automatically passed to Model.beforeFind
.
$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)
Custom options can be read via getOptions()
:
$query->applyOptions([ 'fields' => ['id', 'name'], 'custom' => 'value', ]);
Here $options
will hold ['custom' => 'value']
(the fields
option will be applied to the query instead of being stored, as it's a query clause related option):
$options = $query->getOptions();
array<string, mixed>
$options The options to be applied
$this
bind(string|int $param, mixed $value, string|int|null $type = null): $this
Associates a query placeholder to a value and a type.
$query->bind(':id', 1, 'integer');
string|int
$param placeholder to be replaced with quoted version of $value
mixed
$value The value to be bound
string|int|null
$type optional the mapped type name, used for casting when sending to database
$this
cache(Closure|string|false $key, Psr\SimpleCache\CacheInterface|string $config = 'default'): $this
Enable result caching for this query.
If a query has caching enabled, it will do the following when executed:
// Simple string key + config $query->cache('my_key', 'db_results'); // Function to generate key. $query->cache(function ($q) { $key = serialize($q->clause('select')); $key .= serialize($q->clause('where')); return md5($key); }); // Using a pre-built cache engine. $query->cache('my_key', $engine); // Disable caching $query->cache(false);
Closure|string|false
$key Either the cache key or a function to generate the cache key. When using a function, this query instance will be supplied as an argument.
Psr\SimpleCache\CacheInterface|string
$config optional Either the name of the cache config to use, or a cache config instance.
$this
RuntimeException
chunk(int $size): Cake\Collection\CollectionInterface
Groups the results in arrays of $size rows each.
int
$size Cake\Collection\CollectionInterface
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.
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.
string
$name name of the clause to be returned
mixed
InvalidArgumentException
cleanCopy(): static
Creates a copy of this current query, triggers beforeFind and resets some state.
The following state will be cleared:
This method creates query clones that are useful when working with subqueries.
static
clearContain(): $this
Clears the contained associations from the current query.
$this
clearResult(): $this
Clears the internal result cache and the internal count value from the current query object.
$this
combine(mixed $k, mixed $v, mixed $g = null): Cake\Collection\CollectionInterface
Returns the values of the column $v index by column $k, and grouped by $g.
Cake\Collection\CollectionInterface
contain(array|string $associations, callable|bool $override = false): $this
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.
// 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.
// 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:
$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.// 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 a query builder to add conditions to the containment $query->contain('Authors', function ($q) { return $q->where(...); // add conditions }); // Use special join conditions for multiple containments in the same method call $query->contain([ 'Authors' => [ 'foreignKey' => false, 'queryBuilder' => function ($q) { return $q->where(...); // Add full filtering conditions } ], 'Tags' => function ($q) { return $q->where(...); // add conditions } ]);
If called with an empty first argument and $override
is set to true, the previous list will be emptied.
array|string
$associations List of table aliases to be queried.
callable|bool
$override optional The query builder for the association, or if associations is an array, a bool on whether to override previous list with the one passed defaults to merging previous list with the new one.
$this
count(): int
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
int
countBy(callable|string $field): Cake\Collection\CollectionInterface
Returns the number of unique values for a column
callable|string
$field Cake\Collection\CollectionInterface
counter(callable|null $counter): $this
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
callable|null
$counter The counter value
$this
decorateResults(callable|null $callback, bool $overwrite = false): $this
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.
$query->decorateResults(function ($row) { $row['order_total'] = $row['subtotal'] + ($row['subtotal'] * $row['tax']); return $row; });
callable|null
$callback The callback to invoke when results are fetched.
bool
$overwrite optional Whether this should append or replace all existing decorators.
$this
delete(string|null $table = null): $this
Create a delete query.
This changes the query type to be 'delete'. Can be combined with the where() method to create delete queries.
string|null
$table optional Unused parameter.
$this
disableAutoFields(): $this
Disables automatically appending fields.
$this
disableBufferedResults(): $this
Disables buffered results.
Disabling buffering will consume less memory as fetched results are not remembered for future iterations.
$this
disableHydration(): $this
Disable hydrating entities.
Disabling hydration will cause array results to be returned for the query instead of entities.
$this
disableResultsCasting(): $this
Disables result casting.
When disabled, the fields will be returned as received from the database driver (which in most environments means they are being returned as strings), which can improve performance with larger datasets.
$this
distinct(Cake\Database\ExpressionInterface|array|string|bool $on = [], bool $overwrite = false): $this
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.
// 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);
Cake\Database\ExpressionInterface|array|string|bool
$on optional Enable/disable distinct class or list of fields to be filtered on
bool
$overwrite optional whether to reset fields with passed list or not
$this
each(callable $c): Cake\Collection\CollectionInterface
Passes each of the query results to the callable
callable
$c Cake\Collection\CollectionInterface
eagerLoaded(bool $value): $this
Sets the query instance to be an eager loaded query. If no argument is passed, the current configured query _eagerLoaded
value is returned.
bool
$value Whether to eager load.
$this
enableAutoFields(bool $value = true): $this
Sets whether the ORM should automatically append fields.
By default calling select() will disable auto-fields. You can re-enable auto-fields with this method.
bool
$value optional Set true to enable, false to disable.
$this
enableBufferedResults(bool $enable = true): $this
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.
bool
$enable optional Whether to enable buffering
$this
enableHydration(bool $enable = true): $this
Toggle hydrating entities.
If set to false array results will be returned for the query.
bool
$enable optional Use a boolean to set the hydration mode.
$this
enableResultsCasting(): $this
Enables result casting.
When enabled, the fields in the results returned by this Query will be cast to their corresponding PHP data type.
$this
epilog(Cake\Database\ExpressionInterface|string|null $expression = null): $this
A string or expression that will be appended to the generated query
$query->select('id')->where(['author_id' => 1])->epilog('FOR UPDATE'); $query ->insert('articles', ['title']) ->values(['author_id' => 1]) ->epilog('RETURNING id');
Epliog content is raw SQL and not suitable for use with user supplied data.
Cake\Database\ExpressionInterface|string|null
$expression optional The expression to be appended
$this
every(callable $c): bool
Returns true if all the results pass the callable test
callable
$c bool
execute(): Cake\Database\StatementInterface
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.
Cake\Database\StatementInterface
expr(Cake\Database\ExpressionInterface|array|string|null $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.
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->expr(); // Returns an empty expression object $expression = $query->expr('Table.column = Table2.column'); // Return a raw SQL expression
Cake\Database\ExpressionInterface|array|string|null
$rawExpression optional A string, array or anything you want wrapped in an expression object
Cake\Database\Expression\QueryExpression
extract(mixed $field): Cake\Collection\CollectionInterface
Extracts a single column from each row
Cake\Collection\CollectionInterface
filter(callable $c = null): Cake\Collection\CollectionInterface
Keeps the results using passing the callable test
callable
$c optional Cake\Collection\CollectionInterface
find(string $finder, array<string, mixed> $options = []): static
Apply custom finds to against an existing query object.
Allows custom find methods to be combined and applied to each other.
$repository->find('all')->find('recent');
The above is an example of stacking multiple finder methods onto a single query.
string
$finder The finder method to use.
array<string, mixed>
$options optional The options for the finder.
static
first(): Cake\Datasource\EntityInterface|array|null
Returns the first result out of executing this query, if the query has not been executed before, it will set the limit clause to 1 for performance reasons.
$singleUser = $query->select(['id', 'username'])->first();
Cake\Datasource\EntityInterface|array|null
firstOrFail(): Cake\Datasource\EntityInterface|array
Get the first result from the executing query or raise an exception.
Cake\Datasource\EntityInterface|array
Cake\Datasource\Exception\RecordNotFoundException
formatResults(callable|null $formatter = null, int|bool $mode = self::APPEND): $this
Registers a new formatter callback function that is to be executed when trying to fetch the results from the database.
If the second argument is set to true, it will erase previous formatters and replace them with the passed first argument.
Callbacks are required to return an iterator object, which will be used as the return value for this query's result. Formatter functions are applied after all the MapReduce
routines for this query have been executed.
Formatting callbacks will receive two arguments, the first one being an object implementing \Cake\Collection\CollectionInterface
, that can be traversed and modified at will. The second one being the query instance on which the formatter callback is being applied.
Usually the query instance received by the formatter callback is the same query instance on which the callback was attached to, except for in a joined association, in that case the callback will be invoked on the association source side query, and it will receive that query instance instead of the one on which the callback was originally attached to - see the examples below!
Return all results from the table indexed by id:
$query->select(['id', 'name'])->formatResults(function ($results) { return $results->indexBy('id'); });
Add a new column to the ResultSet:
$query->select(['name', 'birth_date'])->formatResults(function ($results) { return $results->map(function ($row) { $row['age'] = $row['birth_date']->diff(new DateTime)->y; return $row; }); });
Add a new column to the results with respect to the query's hydration configuration:
$query->formatResults(function ($results, $query) { return $results->map(function ($row) use ($query) { $data = [ 'bar' => 'baz', ]; if ($query->isHydrationEnabled()) { $row['foo'] = new Foo($data) } else { $row['foo'] = $data; } return $row; }); });
Retaining access to the association target query instance of joined associations, by inheriting the contain callback's query argument:
// Assuming a `Articles belongsTo Authors` association that uses the join strategy $articlesQuery->contain('Authors', function ($authorsQuery) { return $authorsQuery->formatResults(function ($results, $query) use ($authorsQuery) { // Here `$authorsQuery` will always be the instance // where the callback was attached to. // The instance passed to the callback in the second // argument (`$query`), will be the one where the // callback is actually being applied to, in this // example that would be `$articlesQuery`. // ... return $results; }); });
callable|null
$formatter optional The formatting callable.
int|bool
$mode optional Whether to overwrite, append or prepend the formatter.
$this
InvalidArgumentException
from(array|string $tables = [], bool $overwrite = false): $this
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.
$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
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.
bool
$overwrite optional whether to reset tables with passed list or not
$this
func(): Cake\Database\FunctionsBuilder
Returns an instance of a functions builder object that can be used for generating arbitrary SQL functions.
$query->func()->count('*'); $query->func()->dateDiff(['2012-01-05', '2012-01-02'])
Cake\Database\FunctionsBuilder
getConnection(): Cake\Database\Connection
Gets the connection instance to be used for executing and transforming this query.
Cake\Database\Connection
getContain(): array
array
getDefaultTypes(): array<int|string, string>
Gets default types of current type map.
array<int|string, string>
getEagerLoader(): Cake\ORM\EagerLoader
Returns the currently configured instance.
Cake\ORM\EagerLoader
getIterator(): Cake\Datasource\ResultSetInterface
Executes this query and returns a results iterator. This function is required for implementing the IteratorAggregate interface and allows the query to be iterated without having to call execute() manually, thus making it look like a result set instead of the query itself.
Cake\Datasource\ResultSetInterface
getMapReducers(): array
Returns the list of previously registered map reduce routines.
array
getOptions(): array
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.
$query->applyOptions(['doABarrelRoll' => true, 'fields' => ['id', 'name']); $query->getOptions(); // Returns ['doABarrelRoll' => true]
array
getRepository(): Cake\ORM\Table
Returns the default table object that will be used by this query, that is, the table that will appear in the from clause.
Cake\ORM\Table
getResultFormatters(): array<callable>
Returns the list of previously registered format routines.
array<callable>
getSelectTypeMap(): Cake\Database\TypeMap
Gets the TypeMap class where the types for each of the fields in the select clause are stored.
Cake\Database\TypeMap
getTypeMap(): Cake\Database\TypeMap
Returns the existing type map.
Cake\Database\TypeMap
getValueBinder(): Cake\Database\ValueBinder
Returns the currently used ValueBinder instance.
A ValueBinder is responsible for generating query placeholders and temporarily associate values to those placeholders so that they can be passed correctly to the statement object.
Cake\Database\ValueBinder
group(Cake\Database\ExpressionInterface|array|string $fields, bool $overwrite = false): $this
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.
// Produces GROUP BY id, title $query->group(['id', 'title']); // Produces GROUP BY title $query->group('title');
Group fields are not suitable for use with user supplied data as they are not sanitized by the query builder.
Cake\Database\ExpressionInterface|array|string
$fields fields to be added to the list
bool
$overwrite optional whether to reset fields with passed list or not
$this
groupBy(callable|string $field): Cake\Collection\CollectionInterface
In-memory group all results by the value of a column.
callable|string
$field Cake\Collection\CollectionInterface
having(Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions = null, array<string, string> $types = [], bool $overwrite = false): $this
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.
Having fields are not suitable for use with user supplied data as they are not sanitized by the query builder.
Cake\Database\ExpressionInterfaceClosure|array|string|null
$conditions optional The having conditions.
array<string, string>
$types optional Associative array of type names used to bind values to query
bool
$overwrite optional whether to reset conditions with passed list or not
$this
identifier(string $identifier): Cake\Database\ExpressionInterface
Creates an expression that refers to an identifier. Identifiers are used to refer to field names and allow the SQL compiler to apply quotes or escape the identifier.
The value is used as is, and you might be required to use aliases or include the table reference in the identifier. Do not use this method to inject SQL methods or logical statements.
$query->newExpr()->lte('count', $query->identifier('total'));
string
$identifier The identifier for an expression
Cake\Database\ExpressionInterface
indexBy(callable|string $callback): Cake\Collection\CollectionInterface
Returns the results indexed by the value of a column.
callable|string
$callback Cake\Collection\CollectionInterface
innerJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions = [], array<string, string> $types = []): $this
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 method's description for further details.
array<string, mixed>|string
$table The table to join with
Cake\Database\ExpressionInterface|array|string
$conditions optional The conditions to use for joining.
array<string, string>
$types optional a list of types associated to the conditions used for converting values to the corresponding database representation.
$this
innerJoinWith(string $assoc, callable|null $builder = null): $this
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.
// 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.
string
$assoc The association to join with
callable|null
$builder optional a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields
$this
insert(array $columns, array<int|string, string> $types = []): $this
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.
array
$columns The columns to insert into.
array<int|string, string>
$types optional A map between columns & their datatypes.
$this
into(string $table): $this
Set the table name for insert queries.
string
$table The table name to insert into.
$this
isAutoFieldsEnabled(): bool|null
Gets whether the ORM should automatically append fields.
By default calling select() will disable auto-fields. You can re-enable auto-fields with enableAutoFields().
bool|null
isBufferedResultsEnabled(): bool
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.
bool
isEagerLoaded(): bool
Returns the current configured query _eagerLoaded
value
bool
isEmpty(): bool
Returns true if this query found no results.
bool
isHydrationEnabled(): bool
Returns the current hydration mode.
bool
isResultsCastingEnabled(): bool
Returns whether result casting is enabled/disabled.
When enabled, the fields in the results returned by this Query will be casted to their corresponding PHP data type.
When disabled, the fields will be returned as received from the database driver (which in most environments means they are being returned as strings), which can improve performance with larger datasets.
bool
join(array<string, mixed>|string $tables, array<string, string> $types = [], bool $overwrite = false): $this
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 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"
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'])
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
array<string, mixed>|string
$tables list of tables to be joined in the query
array<string, string>
$types optional Associative array of type names used to bind values to query
bool
$overwrite optional whether to reset joins with passed list or not
$this
jsonSerialize(): Cake\Datasource\ResultSetInterface
Executes the query and converts the result set into JSON.
Part of JsonSerializable interface.
Cake\Datasource\ResultSetInterface
last(): mixed
Return the last row of the query result
mixed
leftJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions = [], array $types = []): $this
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.
array<string, mixed>|string
$table The table to join with
Cake\Database\ExpressionInterface|array|string
$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.
$this
leftJoinWith(string $assoc, callable|null $builder = null): $this
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.
// Get the count of articles per user $usersQuery ->select(['total_articles' => $query->func()->count('Articles.id')]) ->leftJoinWith('Articles') ->group(['Users.id']) ->enableAutoFields();
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();
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
// 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.
string
$assoc The association to join with
callable|null
$builder optional a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields
$this
limit(Cake\Database\ExpressionInterface|int|null $limit): $this
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.
$query->limit(10) // generates LIMIT 10 $query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)
Cake\Database\ExpressionInterface|int|null
$limit number of records to be returned
$this
map(callable $c): Cake\Collection\CollectionInterface
Modifies each of the results using the callable
callable
$c Cake\Collection\CollectionInterface
mapReduce(callable|null $mapper = null, callable|null $reducer = null, bool $overwrite = false): $this
Register a new MapReduce routine to be executed on top of the database results Both the mapper and caller callable should be invokable objects.
The MapReduce routing will only be run when the query is executed and the first result is attempted to be fetched.
If the third argument is set to true, it will erase previous map reducers and replace it with the arguments passed.
callable|null
$mapper optional The mapper callable.
callable|null
$reducer optional The reducing function.
bool
$overwrite optional Set to true to overwrite existing map + reduce functions.
$this
matching(string $assoc, callable|null $builder = null): $this
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.
// 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:
// 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.
// 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.
string
$assoc The association to filter by
callable|null
$builder optional a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields
$this
max(mixed $field): mixed
Returns the maximum value for a single column in all the results.
mixed
min(mixed $field): mixed
Returns the minimum value for a single column in all the results.
mixed
modifier(Cake\Database\ExpressionInterface|array|string $modifiers, bool $overwrite = false): $this
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.
// 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
Cake\Database\ExpressionInterface|array|string
$modifiers modifiers to be applied to the query
bool
$overwrite optional whether to reset order with field list or not
$this
nest(mixed $k, mixed $p, mixed $n = 'children'): Cake\Collection\CollectionInterface
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.
Cake\Collection\CollectionInterface
newExpr(Cake\Database\ExpressionInterface|array|string|null $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.
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->expr(); // Returns an empty expression object $expression = $query->expr('Table.column = Table2.column'); // Return a raw SQL expression
Cake\Database\ExpressionInterface|array|string|null
$rawExpression optional A string, array or anything you want wrapped in an expression object
Cake\Database\Expression\QueryExpression
notMatching(string $assoc, callable|null $builder = null): $this
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.
// 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:
// 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.
// 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.
string
$assoc The association to filter by
callable|null
$builder optional a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields
$this
offset(Cake\Database\ExpressionInterface|int|null $offset): $this
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.
$query->offset(10) // generates OFFSET 10 $query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
Cake\Database\ExpressionInterface|int|null
$offset number of records to be skipped
$this
order(Cake\Database\ExpressionInterfaceClosure|array|string $fields, bool $overwrite = false): $this
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.
$query->order(['title' => 'DESC', 'author_id' => 'ASC']);
Produces:
ORDER BY title DESC, author_id ASC
$query ->order(['title' => $query->newExpr('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()
.
Cake\Database\ExpressionInterfaceClosure|array|string
$fields fields to be added to the list
bool
$overwrite optional whether to reset order with field list or not
$this
orderAsc(Cake\Database\ExpressionInterfaceClosure|string $field, bool $overwrite = false): $this
Add an ORDER BY clause with an ASC direction.
This method allows you to set complex expressions as order conditions unlike order()
Order fields are not suitable for use with user supplied data as they are not sanitized by the query builder.
Cake\Database\ExpressionInterfaceClosure|string
$field The field to order on.
bool
$overwrite optional Whether to reset the order clauses.
$this
orderDesc(Cake\Database\ExpressionInterfaceClosure|string $field, bool $overwrite = false): $this
Add an ORDER BY clause with a DESC direction.
This method allows you to set complex expressions as order conditions unlike order()
Order fields are not suitable for use with user supplied data as they are not sanitized by the query builder.
Cake\Database\ExpressionInterfaceClosure|string
$field The field to order on.
bool
$overwrite optional Whether to reset the order clauses.
$this
page(int $num, int|null $limit = null): $this
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 must start at 1.
int
$num The page number you want.
int|null
$limit optional The number of rows you want in the page. If null the current limit clause will be used.
$this
InvalidArgumentException
reduce(callable $c, mixed $zero = null): mixed
Folds all the results into a single value using the callable.
callable
$c mixed
reject(callable $c): Cake\Collection\CollectionInterface
Removes the results passing the callable test
callable
$c Cake\Collection\CollectionInterface
removeJoin(string $name): $this
Remove a join if it has been defined.
Useful when you are redefining joins or want to re-order the join clauses.
string
$name The alias/name of the join to remove.
$this
repository(Cake\Datasource\RepositoryInterface $repository): $this
Set the default Table object that will be used by this query and form the FROM
clause.
Cake\Datasource\RepositoryInterface
$repository The default table object to use
$this
rightJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions = [], array $types = []): $this
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.
array<string, mixed>|string
$table The table to join with
Cake\Database\ExpressionInterface|array|string
$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.
$this
rowCountAndClose(): int
Executes the SQL of this query and immediately closes the statement before returning the row count of records changed.
This method can be used with UPDATE and DELETE queries, but is not recommended for SELECT queries and is not used to count records.
$rowCount = $query->update('articles') ->set(['published'=>true]) ->where(['published'=>false]) ->rowCountAndClose();
The above example will change the published column to true for all false records, and return the number of records that were updated.
int
sample(int $size = 10): Cake\Collection\CollectionInterface
In-memory shuffle the results and return a subset of them.
int
$size optional Cake\Collection\CollectionInterface
select(Cake\Database\ExpressionInterface|callable|array|string $fields = [], bool $overwrite = false): $this
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 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.
$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::enableAutoFields()
to select the default fields from the table.
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.
Cake\Database\ExpressionInterface|callable|array|string
$fields optional Fields to be added to the list.
bool
$overwrite optional whether to reset fields with passed list or not
$this
selectAllExcept(Cake\ORM\TableCake\ORM\Association $table, array<string> $excludedFields, bool $overwrite = false): $this
All the fields associated with the passed table except the excluded fields will be added to the select clause of the query. Passed excluded fields should not be aliased. After the first call to this method, a second call cannot be used to remove fields that have already been added to the query by the first. If you need to change the list after the first call, pass overwrite boolean true which will reset the select clause removing all previous additions.
Cake\ORM\TableCake\ORM\Association
$table The table to use to get an array of columns
array<string>
$excludedFields The un-aliased column names you do not want selected from $table
bool
$overwrite optional Whether to reset/remove previous selected fields
$this
InvalidArgumentException
set(Cake\Database\Expression\QueryExpressionClosure|array|string $key, mixed $value = null, array<string, string>|string $types = []): $this
Set one or many fields to update.
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'); });
Cake\Database\Expression\QueryExpressionClosure|array|string
$key The column name or array of keys
mixed
$value optional 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<string, string>|string
$types optional The column types to treat data as.
$this
setConnection(Cake\Database\Connection $connection): $this
Sets the connection instance to be used for executing and transforming this query.
Cake\Database\Connection
$connection Connection instance
$this
setDefaultTypes(array<int|string, string> $types): $this
Overwrite the default type mappings for fields in the implementing object.
This method is useful if you need to set type mappings that are shared across multiple functions/expressions in a query.
To add a default without overwriting existing ones use getTypeMap()->addDefaults()
array<int|string, string>
$types The array of types to set.
$this
setEagerLoader(Cake\ORM\EagerLoader $instance): $this
Sets the instance of the eager loader class to use for loading associations and storing containments.
Cake\ORM\EagerLoader
$instance The eager loader to use.
$this
setResult(iterable $results): $this
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.
iterable
$results The results this query should return.
$this
setSelectTypeMap(Cake\Database\TypeMap $typeMap): $this
Sets the TypeMap class where the types for each of the fields in the select clause are stored.
Cake\Database\TypeMap
$typeMap The map object to use
$this
setTypeMap(Cake\Database\TypeMap|array $typeMap): $this
Creates a new TypeMap if $typeMap is an array, otherwise exchanges it for the given one.
Cake\Database\TypeMap|array
$typeMap Creates a TypeMap if array, otherwise sets the given TypeMap
$this
setValueBinder(Cake\Database\ValueBinder|null $binder): $this
Overwrite the current value binder
A ValueBinder is responsible for generating query placeholders and temporarily associate values to those placeholders so that they can be passed correctly to the statement object.
Cake\Database\ValueBinder|null
$binder The binder or null to disable binding.
$this
shuffle(): Cake\Collection\CollectionInterface
In-memory randomize the order the results are returned
Cake\Collection\CollectionInterface
skip(int $howMany): Cake\Collection\CollectionInterface
Skips some rows from the start of the query result.
int
$howMany Cake\Collection\CollectionInterface
some(callable $c): bool
Returns true if at least one of the results pass the callable test
callable
$c bool
sortBy(mixed $callback, int $dir): Cake\Collection\CollectionInterface
Sorts the query with the callback
int
$dir Cake\Collection\CollectionInterface
sql(Cake\Database\ValueBinder|null $binder = null): string
Returns the SQL representation of this object.
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.
Cake\Database\ValueBinder|null
$binder optional string
stopWhen(callable $c): Cake\Collection\CollectionInterface
Returns each row until the callable returns true.
callable
$c Cake\Collection\CollectionInterface
subquery(Cake\ORM\Table $table): static
Returns a new Query that has automatic field aliasing disabled.
Cake\ORM\Table
$table The table this query is starting on
static
sumOf(callable|string $field): float
Returns the sum of all values for a single column
callable|string
$field float
take(int $size = 1, int $from = 0): Cake\Collection\CollectionInterface
In-memory limit and offset for the query results.
int
$size optional int
$from optional Cake\Collection\CollectionInterface
toArray(): array
Returns a key-value array with the results of this query.
array
toList(): array
Returns a numerically indexed array with the results of this query.
array
traverse(callable $callback): $this
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.
$query->select(['title'])->from('articles')->traverse(function ($value, $clause) { if ($clause === 'select') { var_dump($value); } });
callable
$callback A function or callable to be executed for each part
$this
traverseExpressions(callable $callback): $this
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.
callable
$callback the function to be executed for each ExpressionInterface found inside this query.
$this
traverseParts(callable $visitor, array<string> $parts): $this
Will iterate over the provided parts.
Traversing functions can aggregate results using variables in the closure or instance variables. This method can be used to traverse a subset of query parts in order to render a SQL 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.
$query->select(['title'])->from('articles')->traverse(function ($value, $clause) { if ($clause === 'select') { var_dump($value); } }, ['select', 'from']);
callable
$visitor A function or callable to be executed for each part
array<string>
$parts The list of query parts to traverse
$this
triggerBeforeFind(): void
Trigger the beforeFind event on the query's repository object.
Will not trigger more than once, and only for select queries.
void
type(): string
Returns the type of this query (select, insert, update, delete)
string
union(Cake\Database\Query|string $query, bool $overwrite = false): $this
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().
$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
Cake\Database\Query|string
$query full SQL query to be used in UNION operator
bool
$overwrite optional whether to reset the list of queries to be operated or not
$this
unionAll(Cake\Database\Query|string $query, bool $overwrite = false): $this
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
Cake\Database\Query|string
$query full SQL query to be used in UNION operator
bool
$overwrite optional whether to reset the list of queries to be operated or not
$this
update(Cake\Database\ExpressionInterface|string $table = null): $this
Create an update query.
This changes the query type to be 'update'. Can be combined with set() and where() methods to create update queries.
Cake\Database\ExpressionInterface|string
$table optional Unused parameter.
$this
values(Cake\Database\Expression\ValuesExpressionCake\Database\Query|array $data): $this
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.
Cake\Database\Expression\ValuesExpressionCake\Database\Query|array
$data The data to insert.
$this
Cake\Database\Exception\DatabaseException
where(Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions = null, array<string, string> $types = [], bool $overwrite = false): $this
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.
$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.
$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.
$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.
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); });
WHERE title != 'Hello World' AND (id = 1 OR (id > 2 AND id < 10))
$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.
Cake\Database\ExpressionInterfaceClosure|array|string|null
$conditions optional The conditions to filter on.
array<string, string>
$types optional Associative array of type names used to bind values to query
bool
$overwrite optional whether to reset conditions with passed list or not
$this
whereInList(string $field, array $values, array<string, mixed> $options = []): $this
Adds an IN condition or set of conditions to be used in the WHERE clause for this query.
This method does allow empty inputs in contrast to where() if you set 'allowEmpty' to true. Be careful about using it without proper sanity checks.
Options:
types
- Associative array of type names used to bind values to queryallowEmpty
- Allow empty array.string
$field Field
array
$values Array of values
array<string, mixed>
$options optional Options
$this
whereNotInList(string $field, array $values, array<string, mixed> $options = []): $this
Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query.
This method does allow empty inputs in contrast to where() if you set 'allowEmpty' to true. Be careful about using it without proper sanity checks.
string
$field Field
array
$values Array of values
array<string, mixed>
$options optional Options
$this
whereNotInListOrNull(string $field, array $values, array<string, mixed> $options = []): $this
Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query. This also allows the field to be null with a IS NULL condition since the null value would cause the NOT IN condition to always fail.
This method does allow empty inputs in contrast to where() if you set 'allowEmpty' to true. Be careful about using it without proper sanity checks.
string
$field Field
array
$values Array of values
array<string, mixed>
$options optional Options
$this
whereNotNull(Cake\Database\ExpressionInterface|array|string $fields): $this
Convenience method that adds a NOT NULL condition to the query
Cake\Database\ExpressionInterface|array|string
$fields A single field or expressions or a list of them that should be not null.
$this
whereNull(Cake\Database\ExpressionInterface|array|string $fields): $this
Convenience method that adds a IS NULL condition to the query
Cake\Database\ExpressionInterface|array|string
$fields A single field or expressions or a list of them that should be null.
$this
window(string $name, Cake\Database\Expression\WindowExpressionClosure $window, bool $overwrite = false): $this
Adds a named window expression.
You are responsible for adding windows in the order your database requires.
string
$name Window name
Cake\Database\Expression\WindowExpressionClosure
$window Window expression
bool
$overwrite optional Clear all previous query window expressions
$this
with(Cake\Database\Expression\CommonTableExpressionClosure $cte, bool $overwrite = false): $this
Adds a new common table expression (CTE) to the query.
Common table expressions can either be passed as preconstructed expression objects:
$cte = new \Cake\Database\Expression\CommonTableExpression( 'cte', $connection ->newQuery() ->select('*') ->from('articles') ); $query->with($cte);
or returned from a closure, which will receive a new common table expression object as the first argument, and a new blank query object as the second argument:
$query->with(function ( \Cake\Database\Expression\CommonTableExpression $cte, \Cake\Database\Query $query ) { $cteQuery = $query ->select('*') ->from('articles'); return $cte ->name('cte') ->query($cteQuery); });
Cake\Database\Expression\CommonTableExpressionClosure
$cte The CTE to add.
bool
$overwrite optional Whether to reset the list of CTEs.
$this
zip(arrayTraversable $c): Cake\Collection\CollectionInterface
Returns the first result of both the query and $c in an array, then the second results and so on.
arrayTraversable
$c Cake\Collection\CollectionInterface
zipWith(mixed $collections, callable $callable): Cake\Collection\CollectionInterface
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.
callable
$callable Cake\Collection\CollectionInterface
Tracks whether the original query should include fields from the top level table.
bool|null
True if the beforeFind event has already been triggered for this query
bool
A query cacher instance if this query has caching enabled.
Cake\Datasource\QueryCacher|null
Connection instance to be used to execute this query.
Cake\Database\Connection
A callable function that can be used to calculate the total amount of records this query will match when not using limit
callable|null
The list of query clauses to traverse for generating a DELETE statement
array<string>
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.
bool
Whether the query is standalone or the product of an eager load operation.
bool
Instance of a class responsible for storing association containments and for eager loading them when this query is executed
Cake\ORM\EagerLoader|null
List of formatter classes or callbacks that will post-process the results when fetched
array<callable>
Instance of functions builder object used for generating arbitrary SQL functions.
Cake\Database\FunctionsBuilder|null
Whether the user select any fields before being executed, this is used to determined if any fields should be automatically be selected.
bool|null
Whether to hydrate results into entity objects
bool
The list of query clauses to traverse for generating an INSERT statement
array<string>
Statement object resulting from executing this query.
Cake\Database\StatementInterface|null
List of map-reduce routines that should be applied over the query result
array
Holds any custom options passed using applyOptions that could not be processed by any method in this class.
array
List of SQL parts that will be used to build this query.
array<string, mixed>
Instance of a table object this query is bound to.
Cake\ORM\Table
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.
array<callable>
A ResultSet.
When set, query execution will be bypassed.
iterable|null
The COUNT(*) for the query.
When set, count query execution will be bypassed.
int|null
The list of query clauses to traverse for generating a SELECT statement
array<string>
The Type map for fields in the select clause
Cake\Database\TypeMap|null
Type of this query (select, insert, update, delete).
string
Cake\Database\TypeMap|null
The list of query clauses to traverse for generating an UPDATE statement
array<string>
Boolean for tracking whether buffered results are enabled.
bool
The object responsible for generating query placeholders and temporarily store values associated to each of those.
Cake\Database\ValueBinder|null
Whether aliases are generated for fields.
bool
Tracking flag to disable casting
bool
© 2005–present 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/4.4/class-Cake.ORM.Query.html