Class Query | CakePHP 4.6

  • __clone() public

    Handles clearing iterator and cloning all expressions and value binders.

  • __construct() public

    Constructor.

  • __debugInfo() public

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

  • __toString() public

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

  • _conjugate() protected

    Helper function used to build conditions by composing QueryExpression objects.

  • _decorateStatement() protected

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

  • _deprecatedMethod() protected

    Helper for Query deprecation methods.

  • _dirty() protected

    Marks a query as dirty, removing any preprocessed information from in memory caching.

  • _expressionsVisitor() protected

    Query parts traversal method used by traverseExpressions()

  • _makeJoin() protected

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

  • andHaving() public

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

  • andWhere() public

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

  • bind() public

    Associates a query placeholder to a value and a type.

  • clause() public

    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.

  • decorateResults() public

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

  • delete() public

    Create a delete query.

  • disableBufferedResults() public deprecated

    Disables buffered results.

  • disableResultsCasting() public

    Disables result casting.

  • distinct() public

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

  • enableBufferedResults() public deprecated

    Enables/Disables buffered results.

  • enableResultsCasting() public

    Enables result casting.

  • epilog() public

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

  • execute() public

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

  • expr() public

    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.

  • from() public

    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.

  • func() public

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

  • getConnection() public

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

  • getConnectionRole() public

    Returns the connection role ('read' or 'write')

  • getDefaultTypes() public

    Gets default types of current type map.

  • getIterator() public

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

  • getSelectTypeMap() public

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

  • getTypeMap() public

    Returns the existing type map.

  • getValueBinder() public

    Returns the currently used ValueBinder instance.

  • group() public

    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.

  • having() public

    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.

  • identifier() public

    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.

  • innerJoin() public

    Adds a single INNER JOIN clause to the query.

  • insert() public

    Create an insert query.

  • into() public

    Set the table name for insert queries.

  • isBufferedResultsEnabled() public deprecated

    Returns whether buffered results are enabled/disabled.

  • isResultsCastingEnabled() public

    Returns whether result casting is enabled/disabled.

  • join() public

    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.

  • leftJoin() public

    Adds a single LEFT JOIN clause to the query.

  • limit() public

    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.

  • modifier() public

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

  • newExpr() public

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

  • offset() public

    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.

  • order() public

    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.

  • orderAsc() public

    Add an ORDER BY clause with an ASC direction.

  • orderDesc() public

    Add an ORDER BY clause with a DESC direction.

  • page() public

    Set the page of results you want.

  • removeJoin() public

    Remove a join if it has been defined.

  • rightJoin() public

    Adds a single RIGHT JOIN clause to the query.

  • rowCountAndClose() public

    Executes the SQL of this query and immediately closes the statement before returning the row count of records changed.

  • select() public

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

  • set() public

    Set one or many fields to update.

  • setConnection() public

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

  • setDefaultTypes() public

    Overwrite the default type mappings for fields in the implementing object.

  • setSelectTypeMap() public

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

  • setTypeMap() public

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

  • setValueBinder() public

    Overwrite the current value binder

  • sql() public

    Returns the SQL representation of this object.

  • traverse() public

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

  • traverseExpressions() public

    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.

  • traverseParts() public

    Will iterate over the provided parts.

  • type() public

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

  • union() public

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

  • unionAll() public

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

  • update() public

    Create an update query.

  • values() public

    Set the values for an insert query.

  • where() public

    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.

  • whereInList() public

    Adds an IN condition or set of conditions to be used in the WHERE clause for this query.

  • whereNotInList() public

    Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query.

  • whereNotInListOrNull() public

    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.

  • whereNotNull() public

    Convenience method that adds a NOT NULL condition to the query

  • whereNull() public

    Convenience method that adds a IS NULL condition to the query

  • window() public

    Adds a named window expression.

  • with() public

    Adds a new common table expression (CTE) to the query.

  • Method Detail

    __clone() public

    __clone(): void

    Handles clearing iterator and cloning all expressions and value binders.

    Returns

    void

    __construct() public

    __construct(Cake\Database\Connection $connection)

    Constructor.

    Parameters
    Cake\Database\Connection $connection

    The connection object to be used for transforming and executing this query

    __debugInfo() public

    __debugInfo(): array<string, mixed>

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

    Returns

    array<string, mixed>

    __toString() public

    __toString(): string

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

    Returns

    string

    _conjugate() protected

    _conjugate(string $part, Cake\Database\ExpressionInterface|Closure|array|string|null $append, string $conjunction, array<string, string> $types): void

    Helper function used to build conditions by composing QueryExpression objects.

    Parameters
    string $part

    Name of the query part to append the new part to

    Cake\Database\ExpressionInterface|Closure|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

    Returns

    void

    _decorateStatement() protected

    _decorateStatement(Cake\Database\StatementInterface $statement): Cake\Database\Statement\CallbackStatement|Cake\Database\StatementInterface

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

    Parameters
    Cake\Database\StatementInterface $statement

    to be decorated

    Returns

    Cake\Database\Statement\CallbackStatement|Cake\Database\StatementInterface

    _deprecatedMethod() protected

    _deprecatedMethod(string $method, string $message = ''): void

    Helper for Query deprecation methods.

    Parameters
    string $method

    The method that is invalid.

    string $message optional

    An additional message.

    Returns

    void

    _dirty() protected

    _dirty(): void

    Marks a query as dirty, removing any preprocessed information from in memory caching.

    Returns

    void

    _expressionsVisitor() protected

    _expressionsVisitor(Cake\Database\ExpressionInterface|array<Cake\Database\ExpressionInterface> $expression, Closure $callback): void

    Query parts traversal method used by traverseExpressions()

    Parameters
    Cake\Database\ExpressionInterface|array<Cake\Database\ExpressionInterface> $expression

    Query expression or array of expressions.

    Closure $callback

    The callback to be executed for each ExpressionInterface found inside this query.

    Returns

    void

    _makeJoin() protected

    _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

    Parameters
    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

    Returns

    array

    andHaving() public

    andHaving(Cake\Database\ExpressionInterface|Closure|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.

    Parameters
    Cake\Database\ExpressionInterface|Closure|array|string $conditions

    The AND conditions for HAVING.

    array<string, string> $types optional

    Associative array of type names used to bind values to query

    Returns

    $this

    See Also

    \Cake\Database\Query::andWhere()

    andWhere() public

    andWhere(Cake\Database\ExpressionInterface|Closure|array|string $conditions, array<string, string> $types = []): $this

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

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

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

    Examples:

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

    Will produce:

    WHERE title = 'Hello World' AND author_id = 1

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

    Produces:

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

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

    Generates the following conditions:

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

    Parameters
    Cake\Database\ExpressionInterface|Closure|array|string $conditions

    The conditions to add with AND.

    array<string, string> $types optional

    Associative array of type names used to bind values to query

    Returns

    $this

    See Also

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

    bind() public

    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');
    Parameters
    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

    Returns

    $this

    clause() public

    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.

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

    name of the clause to be returned

    Returns

    mixed

    Throws

    InvalidArgumentException
    When the named clause does not exist.

    decorateResults() public

    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.

    Example

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

    The callback to invoke when results are fetched.

    bool $overwrite optional

    Whether this should append or replace all existing decorators.

    Returns

    $this

    delete() public

    delete(string|null $table = null): $this

    Create a delete query.

    Can be combined with from(), where() and other methods to create delete queries with specific conditions.

    Parameters
    string|null $table optional

    The table to use when deleting.

    Returns

    $this

    disableBufferedResults() public

    disableBufferedResults(): $this

    Disables buffered results.

    Disabling buffering will consume less memory as fetched results are not remembered for future iterations.

    Returns

    $this

    disableResultsCasting() public

    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.

    Returns

    $this

    distinct() public

    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.

    Examples:

    // Filters products with the same name and city
    $query->select(['name', 'city'])->from('products')->distinct();
    
    // Filters products in the same city
    $query->distinct(['city']);
    $query->distinct('city');
    
    // Filter products with the same name
    $query->distinct(['name'], true);
    $query->distinct('name', true);
    Parameters
    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

    Returns

    $this

    enableBufferedResults() public

    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.

    Parameters
    bool $enable optional

    Whether to enable buffering

    Returns

    $this

    enableResultsCasting() public

    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.

    Returns

    $this

    epilog() public

    epilog(Cake\Database\ExpressionInterface|string|null $expression = null): $this

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

    Examples:

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

    Epliog content is raw SQL and not suitable for use with user supplied data.

    Parameters
    Cake\Database\ExpressionInterface|string|null $expression optional

    The expression to be appended

    Returns

    $this

    execute() public

    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.

    Returns

    Cake\Database\StatementInterface

    expr() public

    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
    Parameters
    Cake\Database\ExpressionInterface|array|string|null $rawExpression optional

    A string, array or anything you want wrapped in an expression object

    Returns

    Cake\Database\Expression\QueryExpression

    from() public

    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.

    Examples:

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

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

    bool $overwrite optional

    whether to reset tables with passed list or not

    Returns

    $this

    func() public

    func(): Cake\Database\FunctionsBuilder

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

    Example:

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

    Cake\Database\FunctionsBuilder

    getConnection() public

    getConnection(): Cake\Database\Connection

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

    Returns

    Cake\Database\Connection

    getConnectionRole() public

    getConnectionRole(): string

    Returns the connection role ('read' or 'write')

    Returns

    string

    getDefaultTypes() public

    getDefaultTypes(): array<int|string, string>

    Gets default types of current type map.

    Returns

    array<int|string, string>

    getIterator() public

    getIterator(): Cake\Database\StatementInterface

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

    Returns

    Cake\Database\StatementInterface

    getSelectTypeMap() public

    getSelectTypeMap(): Cake\Database\TypeMap

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

    Returns

    Cake\Database\TypeMap

    getTypeMap() public

    getTypeMap(): Cake\Database\TypeMap

    Returns the existing type map.

    Returns

    Cake\Database\TypeMap

    getValueBinder() public

    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.

    Returns

    Cake\Database\ValueBinder

    group() public

    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.

    Examples:

    // 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.

    Parameters
    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

    Returns

    $this

    having() public

    having(Cake\Database\ExpressionInterface|Closure|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.

    Parameters
    Cake\Database\ExpressionInterface|Closure|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

    Returns

    $this

    See Also

    \Cake\Database\Query::where()

    identifier() public

    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.

    Example

    $query->newExpr()->lte('count', $query->identifier('total'));
    Parameters
    string $identifier

    The identifier for an expression

    Returns

    Cake\Database\ExpressionInterface

    innerJoin() public

    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.

    Parameters
    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.

    Returns

    $this

    insert() public

    insert(array $columns, array<int|string, string> $types = []): $this

    Create an insert query.

    Note calling this method will reset any data previously set with Query::values().

    Parameters
    array $columns

    The columns to insert into.

    array<int|string, string> $types optional

    A map between columns & their datatypes.

    Returns

    $this

    Throws

    RuntimeException
    When there are 0 columns.

    into() public

    into(string $table): $this

    Set the table name for insert queries.

    Parameters
    string $table

    The table name to insert into.

    Returns

    $this

    isBufferedResultsEnabled() public

    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.

    Returns

    bool

    isResultsCastingEnabled() public

    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.

    Returns

    bool

    join() public

    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"

    Using conditions and types

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

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

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

    Overwriting joins

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

    $query->join(['alias' => 'table']); // joins table with as alias
    $query->join(['alias' => 'another_table']); // joins another_table with as alias
    $query->join(['something' => 'different_table'], [], true); // resets joins list
    Parameters
    array<string, 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

    Returns

    $this

    See Also

    \Cake\Database\TypeFactory

    leftJoin() public

    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.

    Parameters
    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.

    Returns

    $this

    limit() public

    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.

    Examples

    $query->limit(10) // generates LIMIT 10
    $query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)
    Parameters
    Cake\Database\ExpressionInterface|int|null $limit

    number of records to be returned

    Returns

    $this

    modifier() public

    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.

    Example:

    // Ignore cache query in MySQL
    $query->select(['name', 'city'])->from('products')->modifier('SQL_NO_CACHE');
    // It will produce the SQL: SELECT SQL_NO_CACHE name, city FROM products
    
    // Or with multiple modifiers
    $query->select(['name', 'city'])->from('products')->modifier(['HIGH_PRIORITY', 'SQL_NO_CACHE']);
    // It will produce the SQL: SELECT HIGH_PRIORITY SQL_NO_CACHE name, city FROM products
    Parameters
    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

    Returns

    $this

    newExpr() public

    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
    Parameters
    Cake\Database\ExpressionInterface|array|string|null $rawExpression optional

    A string, array or anything you want wrapped in an expression object

    Returns

    Cake\Database\Expression\QueryExpression

    offset() public

    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.

    Examples

    $query->offset(10) // generates OFFSET 10
    $query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
    Parameters
    Cake\Database\ExpressionInterface|int|null $offset

    number of records to be skipped

    Returns

    $this

    order() public

    order(Cake\Database\ExpressionInterface|Closure|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.

    Examples:

    $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']);

    and

    $query->order(function ($exp, $query) {
        return [$exp->add(['id % 2 = 0']), 'title' => 'ASC'];
    });

    Will both become:

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

    Order fields/directions are not sanitized by the query builder. You should use an allowed list of fields/directions when passing in user-supplied data to order().

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

    Parameters
    Cake\Database\ExpressionInterface|Closure|array|string $fields

    fields to be added to the list

    bool $overwrite optional

    whether to reset order with field list or not

    Returns

    $this

    orderAsc() public

    orderAsc(Cake\Database\ExpressionInterface|Closure|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.

    Parameters
    Cake\Database\ExpressionInterface|Closure|string $field

    The field to order on.

    bool $overwrite optional

    Whether to reset the order clauses.

    Returns

    $this

    orderDesc() public

    orderDesc(Cake\Database\ExpressionInterface|Closure|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.

    Parameters
    Cake\Database\ExpressionInterface|Closure|string $field

    The field to order on.

    bool $overwrite optional

    Whether to reset the order clauses.

    Returns

    $this

    page() public

    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.

    Parameters
    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.

    Returns

    $this

    Throws

    InvalidArgumentException
    If page number < 1.

    removeJoin() public

    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.

    Parameters
    string $name

    The alias/name of the join to remove.

    Returns

    $this

    rightJoin() public

    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.

    Parameters
    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.

    Returns

    $this

    rowCountAndClose() public

    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.

    Example

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

    Returns

    int

    select() public

    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.

    Examples:

    $query->select(['id', 'title']); // Produces SELECT id, title
    $query->select(['author' => 'author_id']); // Appends author: SELECT id, title, author_id as author
    $query->select('id', true); // Resets the list: SELECT id
    $query->select(['total' => $countQuery]); // SELECT id, (SELECT ...) AS total
    $query->select(function ($query) {
        return ['article_id', 'total' => $query->count('*')];
    })

    By default no fields are selected, if you have an instance of Cake\ORM\Query and try to append fields you should also call Cake\ORM\Query::enableAutoFields() to select the default fields from the table.

    Parameters
    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

    Returns

    $this

    set() public

    set(Cake\Database\Expression\QueryExpression|Closure|array|string $key, mixed $value = null, array<string, string>|string $types = []): $this

    Set one or many fields to update.

    Examples

    Passing a string:

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

    Passing an array:

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

    Passing a callable:

    $query->update('articles')->set(function ($exp) {
      return $exp->eq('title', 'The title', 'string');
    });
    Parameters
    Cake\Database\Expression\QueryExpression|Closure|array|string $key

    The column name or array of keys

    • values to set. This can also be a QueryExpression containing a SQL fragment. It can also be a Closure, that is required to return an expression object.
    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.

    Returns

    $this

    setConnection() public

    setConnection(Cake\Database\Connection $connection): $this

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

    Parameters
    Cake\Database\Connection $connection

    Connection instance

    Returns

    $this

    setDefaultTypes() public

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

    Parameters
    array<int|string, string> $types

    The array of types to set.

    Returns

    $this

    See Also

    \Cake\Database\TypeMap::setDefaults()

    setSelectTypeMap() public

    setSelectTypeMap(Cake\Database\TypeMap $typeMap): $this

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

    Parameters
    Cake\Database\TypeMap $typeMap

    The map object to use

    Returns

    $this

    setTypeMap() public

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

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

    Parameters
    Cake\Database\TypeMap|array $typeMap

    Creates a TypeMap if array, otherwise sets the given TypeMap

    Returns

    $this

    setValueBinder() public

    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.

    Parameters
    Cake\Database\ValueBinder|null $binder

    The binder or null to disable binding.

    Returns

    $this

    sql() public

    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.

    Parameters
    Cake\Database\ValueBinder|null $binder optional

    Value binder that generates parameter placeholders

    Returns

    string

    traverse() public

    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.

    Example

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

    A function or callable to be executed for each part

    Returns

    $this

    traverseExpressions() public

    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.

    Parameters
    callable $callback

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

    Returns

    $this

    traverseParts() public

    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.

    Example

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

    A function or callable to be executed for each part

    array<string> $parts

    The list of query parts to traverse

    Returns

    $this

    type() public

    type(): string

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

    Returns

    string

    union() public

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

    Examples

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

    Will produce:

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

    Parameters
    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

    Returns

    $this

    unionAll() public

    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

    Parameters
    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

    Returns

    $this

    update() public

    update(Cake\Database\ExpressionInterface|string $table): $this

    Create an update query.

    Can be combined with set() and where() methods to create update queries.

    Parameters
    Cake\Database\ExpressionInterface|string $table

    The table you want to update.

    Returns

    $this

    values() public

    values(Cake\Database\Expression\ValuesExpression|Cake\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.

    Parameters
    Cake\Database\Expression\ValuesExpression|Cake\Database\Query|array $data

    The data to insert.

    Returns

    $this

    Throws

    Cake\Database\Exception\DatabaseException
    if you try to set values before declaring columns. Or if you try to set values on non-insert queries.

    where() public

    where(Cake\Database\ExpressionInterface|Closure|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.

    Conditions using operators:

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

    The previous example produces:

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

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

    Nesting conditions with conjunctions:

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

    The previous example produces:

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

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

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

    Would result in:

    WHERE (published = false) OR (published = true)

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

    Using expressions objects:

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

    The previous example produces:

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

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

    Adding conditions in multiple steps:

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

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

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

    Conditions as strings:

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

    The previous example produces:

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

    Please note that when using the array notation or the expression objects, all values will be correctly quoted and transformed to the correspondent database data type automatically for you, thus securing your application from SQL injections. The keys however, are not treated as unsafe input, and should be validated/sanitized.

    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.

    Using null-able values

    When using values that can be null you can use the 'IS' keyword to let the ORM generate the correct SQL based on the value's type

    $query->where([
        'posted >=' => new DateTime('3 days ago'),
        'category_id IS' => $category,
    ]);

    If $category is null - it will actually convert that into category_id IS NULL - if it's 4 it will convert it into category_id = 4

    Parameters
    Cake\Database\ExpressionInterface|Closure|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

    Returns

    $this

    See Also

    \Cake\Database\TypeFactory
    \Cake\Database\Expression\QueryExpression

    whereInList() public

    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 query
    • allowEmpty - Allow empty array.
    Parameters
    string $field

    Field

    array $values

    Array of values

    array<string, mixed> $options optional

    Options

    Returns

    $this

    whereNotInList() public

    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.

    Parameters
    string $field

    Field

    array $values

    Array of values

    array<string, mixed> $options optional

    Options

    Returns

    $this

    whereNotInListOrNull() public

    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.

    Parameters
    string $field

    Field

    array $values

    Array of values

    array<string, mixed> $options optional

    Options

    Returns

    $this

    whereNotNull() public

    whereNotNull(Cake\Database\ExpressionInterface|array|string $fields): $this

    Convenience method that adds a NOT NULL condition to the query

    Parameters
    Cake\Database\ExpressionInterface|array|string $fields

    A single field or expressions or a list of them that should be not null.

    Returns

    $this

    whereNull() public

    whereNull(Cake\Database\ExpressionInterface|array|string $fields): $this

    Convenience method that adds a IS NULL condition to the query

    Parameters
    Cake\Database\ExpressionInterface|array|string $fields

    A single field or expressions or a list of them that should be null.

    Returns

    $this

    window() public

    window(string $name, Cake\Database\Expression\WindowExpression|Closure $window, bool $overwrite = false): $this

    Adds a named window expression.

    You are responsible for adding windows in the order your database requires.

    Parameters
    string $name

    Window name

    Cake\Database\Expression\WindowExpression|Closure $window

    Window expression

    bool $overwrite optional

    Clear all previous query window expressions

    Returns

    $this

    with() public

    with(Cake\Database\Expression\CommonTableExpression|Closure $cte, bool $overwrite = false): $this

    Adds a new common table expression (CTE) to the query.

    Examples:

    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);
    });
    Parameters
    Cake\Database\Expression\CommonTableExpression|Closure $cte

    The CTE to add.

    bool $overwrite optional

    Whether to reset the list of CTEs.

    Returns

    $this

    Property Detail

    $_connection protected

    Connection instance to be used to execute this query.

    Type

    Cake\Database\Connection

    $_deleteParts protected deprecated

    The list of query clauses to traverse for generating a DELETE statement

    Type

    array<string>

    $_dirty protected

    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.

    Type

    bool

    $_functionsBuilder protected

    Instance of functions builder object used for generating arbitrary SQL functions.

    Type

    Cake\Database\FunctionsBuilder|null

    $_insertParts protected deprecated

    The list of query clauses to traverse for generating an INSERT statement

    Type

    array<string>

    $_iterator protected

    Statement object resulting from executing this query.

    Type

    Cake\Database\StatementInterface|null

    $_parts protected

    List of SQL parts that will be used to build this query.

    Type

    array<string, mixed>

    $_resultDecorators protected

    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.

    Type

    array<callable>

    $_selectParts protected deprecated

    The list of query clauses to traverse for generating a SELECT statement

    Type

    array<string>

    $_selectTypeMap protected

    The Type map for fields in the select clause

    Type

    Cake\Database\TypeMap|null

    $_type protected

    Type of this query (select, insert, update, delete).

    Type

    string

    $_typeMap protected

    Type

    Cake\Database\TypeMap|null

    $_updateParts protected deprecated

    The list of query clauses to traverse for generating an UPDATE statement

    Type

    array<string>

    $_useBufferedResults protected deprecated

    Boolean for tracking whether buffered results are enabled.

    Type

    bool

    $_valueBinder protected

    The object responsible for generating query placeholders and temporarily store values associated to each of those.

    Type

    Cake\Database\ValueBinder|null

    $connectionRole protected

    Connection role ('read' or 'write')

    Type

    string

    $typeCastEnabled protected

    Tracking flag to disable casting

    Type

    bool