0 follower

Interface Yiisoft\Db\Query\QueryInterface

ExtendsYiisoft\Db\Expression\ExpressionInterface, Yiisoft\Db\Query\QueryFunctionsInterface, Yiisoft\Db\Query\QueryPartsInterface
Implemented byYiisoft\Db\Query\Query

Defines several methods for building and executing database queries, including methods for selecting data, inserting data, updating data, and deleting data.

It also defines methods for specifying the conditions for a query, as well as methods for pagination and sorting.

It has support for getting one() instance or all().

Allows pagination via limit() and offset().

Sorting is supported via orderBy() and items can be limited to match some conditions using where().

Public Methods

Hide inherited methods

Method Description Defined By
addFor() Adds more FOR parts to the existing ones. Yiisoft\Db\Query\QueryPartsInterface
addGroupBy() Adds more group-by columns to the existing ones. Yiisoft\Db\Query\QueryPartsInterface
addOrderBy() Adds more ORDER BY columns to the query. Yiisoft\Db\Query\QueryPartsInterface
addParams() Adds more parameters to bind to the query. Yiisoft\Db\Query\QueryInterface
addSelect() Add more columns to the SELECT part of the query. Yiisoft\Db\Query\QueryPartsInterface
addWithQuery() Prepends an SQL statement using WITH syntax. Yiisoft\Db\Query\QueryPartsInterface
all() Executes the query and returns all results as an array. Yiisoft\Db\Query\QueryInterface
andFilterCompare() Adds a filtering condition for a specific column and allow the user to choose a filter operator. Yiisoft\Db\Query\QueryPartsInterface
andFilterHaving() Adds HAVING condition to the existing one but ignores Query::isEmpty(). Yiisoft\Db\Query\QueryPartsInterface
andFilterWhere() Adds WHERE condition to the existing one but ignores Query::isEmpty(). Yiisoft\Db\Query\QueryPartsInterface
andHaving() Adds HAVING condition to the existing one. Yiisoft\Db\Query\QueryPartsInterface
andWhere() Adds WHERE condition to the existing one. Yiisoft\Db\Query\QueryPartsInterface
average() Returns the average of the specified column values. Yiisoft\Db\Query\QueryFunctionsInterface
batch() Starts a batch query. Yiisoft\Db\Query\QueryInterface
column() Executes the query and returns the first column of the result. Yiisoft\Db\Query\QueryInterface
count() Returns the number of records. Yiisoft\Db\Query\QueryFunctionsInterface
createCommand() Creates a DB command to execute the query. Yiisoft\Db\Query\QueryInterface
distinct() Sets the value indicating whether to SELECT DISTINCT or not. Yiisoft\Db\Query\QueryPartsInterface
each() Creates data reader to retrieve data row by row. Yiisoft\Db\Query\QueryInterface
emulateExecution() Sets whether to emulate query execution without actually executing a query. Yiisoft\Db\Query\QueryInterface
exists() Returns a value indicating whether the query result has any row of data. Yiisoft\Db\Query\QueryInterface
filterHaving() Sets the HAVING part of the query but ignores Query::isEmpty(). Yiisoft\Db\Query\QueryPartsInterface
filterWhere() Sets the WHERE part of the query but ignores Query::isEmpty(). Yiisoft\Db\Query\QueryPartsInterface
for() Sets the FOR part of the query. Yiisoft\Db\Query\QueryPartsInterface
from() Sets the FROM part of the query. Yiisoft\Db\Query\QueryPartsInterface
getDistinct() Yiisoft\Db\Query\QueryInterface
getFor() Yiisoft\Db\Query\QueryInterface
getFrom() Yiisoft\Db\Query\QueryInterface
getGroupBy() Yiisoft\Db\Query\QueryInterface
getHaving() Yiisoft\Db\Query\QueryInterface
getIndexBy() Yiisoft\Db\Query\QueryInterface
getJoins() Yiisoft\Db\Query\QueryInterface
getLimit() Yiisoft\Db\Query\QueryInterface
getOffset() Yiisoft\Db\Query\QueryInterface
getOrderBy() Yiisoft\Db\Query\QueryInterface
getParams() Yiisoft\Db\Query\QueryInterface
getResultCallback() Returns the callback to be called on all rows of the query result. Yiisoft\Db\Query\QueryInterface
getSelect() Yiisoft\Db\Query\QueryInterface
getSelectOption() Yiisoft\Db\Query\QueryInterface
getTablesUsedInFrom() Returns table names used in from() indexed by aliases. Yiisoft\Db\Query\QueryInterface
getUnions() Yiisoft\Db\Query\QueryInterface
getWhere() Yiisoft\Db\Query\QueryInterface
getWithQueries() Yiisoft\Db\Query\QueryInterface
groupBy() Sets the GROUP BY part of the query. Yiisoft\Db\Query\QueryPartsInterface
having() Initially sets the HAVING part of the query. Yiisoft\Db\Query\QueryPartsInterface
indexBy() Sets the indexBy() property. Yiisoft\Db\Query\QueryPartsInterface
innerJoin() Appends an INNER JOIN part to the query. Yiisoft\Db\Query\QueryPartsInterface
join() Appends a JOIN part to the query. Yiisoft\Db\Query\QueryPartsInterface
leftJoin() Appends a LEFT OUTER JOIN part to the query. Yiisoft\Db\Query\QueryPartsInterface
limit() Sets the LIMIT part of the query. Yiisoft\Db\Query\QueryPartsInterface
max() Returns the maximum of the specified column values. Yiisoft\Db\Query\QueryFunctionsInterface
min() Returns the minimum of the specified column values. Yiisoft\Db\Query\QueryFunctionsInterface
offset() Sets the OFFSET part of the query. Yiisoft\Db\Query\QueryPartsInterface
one() Executes the query and returns a single row of a result. Yiisoft\Db\Query\QueryInterface
orFilterHaving() Adds HAVING condition to the existing one but ignores Query::isEmpty(). Yiisoft\Db\Query\QueryPartsInterface
orFilterWhere() Adds WHERE condition to the existing one but ignores Query::isEmpty(). Yiisoft\Db\Query\QueryPartsInterface
orHaving() Adds HAVING condition to the existing one. Yiisoft\Db\Query\QueryPartsInterface
orWhere() Adds WHERE condition to the existing one. Yiisoft\Db\Query\QueryPartsInterface
orderBy() Sets the ORDER BY part of the query. Yiisoft\Db\Query\QueryPartsInterface
params() Sets the parameters to bind to the query. Yiisoft\Db\Query\QueryInterface
prepare() Prepare for building SQL. Yiisoft\Db\Query\QueryInterface
resultCallback() Sets the callback, to be called on all rows of the query result before returning them. Yiisoft\Db\Query\QueryInterface
rightJoin() Appends a RIGHT OUTER JOIN part to the query. Yiisoft\Db\Query\QueryPartsInterface
scalar() Returns the query results as a scalar value. Yiisoft\Db\Query\QueryInterface
select() Sets the SELECT part of the query. Yiisoft\Db\Query\QueryPartsInterface
selectOption() It allows you to specify more options for the SELECT clause of an SQL statement. Yiisoft\Db\Query\QueryPartsInterface
setFor() Overwrites the FOR part of the query. Yiisoft\Db\Query\QueryPartsInterface
setHaving() Overwrites the HAVING part of the query. Yiisoft\Db\Query\QueryPartsInterface
setJoins() Specify the joins for a SELECT statement in a database query. Yiisoft\Db\Query\QueryPartsInterface
setUnions() Specify queries for a SELECT statement that are combined with UNIONs. Yiisoft\Db\Query\QueryPartsInterface
setWhere() Overwrites the WHERE part of the query. Yiisoft\Db\Query\QueryPartsInterface
shouldEmulateExecution() Yiisoft\Db\Query\QueryInterface
sum() Returns the sum of the specified column values. Yiisoft\Db\Query\QueryFunctionsInterface
union() Appends an SQL statement using UNION operator. Yiisoft\Db\Query\QueryPartsInterface
where() Initially sets the WHERE part of the query. Yiisoft\Db\Query\QueryPartsInterface
withQueries() Specifies the WITH query clause for the query. Yiisoft\Db\Query\QueryPartsInterface
withQuery() Set an SQL statement using WITH syntax. Yiisoft\Db\Query\QueryPartsInterface
withTypecasting() Returns a copy of the instance with enabled or disabled typecasting of values when retrieving records from DB. Yiisoft\Db\Query\QueryInterface

Method Details

Hide inherited methods

addFor() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::addFor()

Adds more FOR parts to the existing ones.

See also:

public abstract addFor( array|string|null $value ): Yiisoft\Db\Query\QueryInterface
$value array|string|null

The value(s) to be set for the FOR part. This can be either a string (for example, 'UPDATE') or a list of strings (such as ['SHARE OF {{t1}}', 'UPDATE OF {{t2}}']) specifying one or several values. null means adding nothing.

                public function addFor(string|array|null $value): static;

            
addGroupBy() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::addGroupBy()

Adds more group-by columns to the existing ones.

See also groupBy().

public abstract addGroupBy( array|Yiisoft\Db\Expression\ExpressionInterface|string $columns ): Yiisoft\Db\Query\QueryInterface
$columns array|Yiisoft\Db\Expression\ExpressionInterface|string

More columns to be grouped by. Columns can be specified in either a string (for example 'id, name') or an array (such as ['id', 'name']). The method will automatically quote the column names unless a column has some parenthesis (which means the column has a DB expression). Note that if your group-by is an expression containing commas, you should always use an array to represent the group-by information. Otherwise, the method won't be able to correctly decide the group-by columns.

Yiisoft\Db\Expression\ExpressionInterface object can be passed to specify the GROUP BY part explicitly in plain SQL. Yiisoft\Db\Expression\ExpressionInterface object can be passed as well.

                public function addGroupBy(array|string|ExpressionInterface $columns): static;

            
addOrderBy() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::addOrderBy()

Adds more ORDER BY columns to the query.

See also orderBy().

public abstract addOrderBy( array|Yiisoft\Db\Expression\ExpressionInterface|string $columns ): Yiisoft\Db\Query\QueryInterface
$columns array|Yiisoft\Db\Expression\ExpressionInterface|string

The columns (and the directions) to be ordered by. Columns can be specified in either a string (for example "id ASC, name DESC") or an array (for example, ['id' => SORT_ASC, 'name' => SORT_DESC]). The method will automatically quote the column names unless a column has some parenthesis (which means the column has a DB expression). Note that if your order-by is an expression containing commas, you should always use an array to represent the order-by information. Otherwise, the method won't be able to correctly decide the order-by columns. Since Yiisoft\Db\Expression\ExpressionInterface an object can be passed to specify the ORDER BY part explicitly in plain SQL.

                public function addOrderBy(array|string|ExpressionInterface $columns): static;

            
addParams() public abstract method

Adds more parameters to bind to the query.

See also params().

public abstract addParams( array $params ): Yiisoft\Db\Query\QueryInterface
$params array

The list of query parameter values indexed by parameter placeholders. For example, [':name' => 'Dan', ':age' => 31].

                public function addParams(array $params): static;

            
addSelect() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::addSelect()

Add more columns to the SELECT part of the query.

Note, that if select() hasn't been specified before, you should include * explicitly if you want to select all remaining columns too:

$query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();

See also select() for more details about the format of this parameter.

public abstract addSelect( array|Yiisoft\Db\Expression\ExpressionInterface|scalar $columns ): Yiisoft\Db\Query\QueryInterface
$columns array|Yiisoft\Db\Expression\ExpressionInterface|scalar

The columns to add to the select.

Version Description
2.0.0 `$columns` can be a scalar value or an array of scalar values.

                public function addSelect(array|bool|float|int|string|ExpressionInterface $columns): static;

            
addWithQuery() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::addWithQuery()

Prepends an SQL statement using WITH syntax.

public abstract addWithQuery( Yiisoft\Db\Query\QueryInterface|string $query, Yiisoft\Db\Expression\ExpressionInterface|string $alias, boolean $recursive false ): Yiisoft\Db\Query\QueryInterface
$query Yiisoft\Db\Query\QueryInterface|string

The SQL statement to append using UNION.

$alias Yiisoft\Db\Expression\ExpressionInterface|string

The query alias in WITH construction. To specify the alias in plain SQL, you may pass an instance of Yiisoft\Db\Expression\ExpressionInterface.

$recursive boolean

Its true if using WITH RECURSIVE and false if using WITH.

                public function addWithQuery(
    QueryInterface|string $query,
    ExpressionInterface|string $alias,
    bool $recursive = false,
): static;

            
all() public abstract method

Executes the query and returns all results as an array.

public abstract all( ): array[]|object[]
return array[]|object[]

All rows of the query result. Each array element is an array or object representing a row of data. Empty array if the query results in nothing.

throws Yiisoft\Db\Exception\Exception
throws Yiisoft\Db\Exception\InvalidConfigException
throws Throwable

                public function all(): array;

            
andFilterCompare() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::andFilterCompare()

Adds a filtering condition for a specific column and allow the user to choose a filter operator.

It adds WHERE condition for the given field and determines the comparison operator based on the first few characters of the given value.

The condition is added in the same way as in andFilterWhere() so \Yiisoft\Db\Query\Query::isEmpty() are ignored.

The new condition and the existing one are joined using the AND operator.

The comparison operator is intelligently determined based on the first few characters in the given value.

In particular, it recognizes the following operators if they appear as the leading characters in the given value:

  • <: the column must be less than the given value.
  • >: the column must be greater than the given value.
  • <=: the column must be less than or equal to the given value.
  • >=: the column must be greater than or equal to the given value.
  • <>: the column must not be the same as the given value.
  • =: the column must be equal to the given value.
  • If operator isn't regognized, the $defaultOperator is used.
public abstract andFilterCompare( string $column, string|null $value, string $defaultOperator '=' ): Yiisoft\Db\Query\QueryInterface
$column string

The column name.

$value string|null

The column value optionally prepended with the comparison operator.

$defaultOperator string

The operator to use when no operator is given in $value. Defaults to =, performing an exact match.

throws Yiisoft\Db\Exception\NotSupportedException

If this query doesn't support filtering.

                public function andFilterCompare(string $column, ?string $value, string $defaultOperator = '='): static;

            
andFilterHaving() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::andFilterHaving()

Adds HAVING condition to the existing one but ignores Query::isEmpty().

The new condition and the existing one will be joined using the AND operator.

This method is similar to andHaving(). The main difference is that this method will remove \Yiisoft\Db\Query\Query::isEmpty().

As a result, this method is best suited for building query conditions based on filter values entered by users.

See also:

public abstract andFilterHaving( array $condition ): Yiisoft\Db\Query\QueryInterface
$condition array

The new HAVING condition. Please refer to having() on how to specify this parameter.

throws Yiisoft\Db\Exception\NotSupportedException

If this query doesn't support filtering.

                public function andFilterHaving(array $condition): static;

            
andFilterWhere() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::andFilterWhere()

Adds WHERE condition to the existing one but ignores Query::isEmpty().

The new condition and the existing one will be joined using the AND operator.

This method is similar to andWhere(). The main difference is that this method will remove \Yiisoft\Db\Query\Query::isEmpty().

As a result, this method is best suited for building query conditions based on filter values entered by users.

See also:

public abstract andFilterWhere( array $condition ): Yiisoft\Db\Query\QueryInterface
$condition array

The new WHERE condition. Please refer to where() on how to specify this parameter.

throws Yiisoft\Db\Exception\NotSupportedException

If this query doesn't support filtering.

                public function andFilterWhere(array $condition): static;

            
andHaving() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::andHaving()

Adds HAVING condition to the existing one.

The new condition and the existing one will be joined using the AND operator.

See also:

public abstract andHaving( array|Yiisoft\Db\Expression\ExpressionInterface|string $condition, array $params = [] ): Yiisoft\Db\Query\QueryInterface
$condition array|Yiisoft\Db\Expression\ExpressionInterface|string

The new HAVING condition. Please refer to where() on how to specify this parameter.

$params array

The parameters (name => value) to be bound to the query.

                public function andHaving(array|string|ExpressionInterface $condition, array $params = []): static;

            
andWhere() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::andWhere()

Adds WHERE condition to the existing one.

The new condition and the existing one will be joined using the AND operator.

See also:

public abstract andWhere( array|Yiisoft\Db\Expression\ExpressionInterface|string $condition, array $params = [] ): Yiisoft\Db\Query\QueryInterface
$condition array|Yiisoft\Db\Expression\ExpressionInterface|string

The new WHERE condition. Please refer to where() on how to specify this parameter.

$params array

The parameters (name => value) to be bound to the query.

                public function andWhere(array|ExpressionInterface|string $condition, array $params = []): static;

            
average() public abstract method

Defined in: Yiisoft\Db\Query\QueryFunctionsInterface::average()

Returns the average of the specified column values.

public abstract average( string $sql ): float|integer|string|null
$sql string

The column name or expression.

return float|integer|string|null

The average of the specified column values.

Note: Make sure you quote column names in the expression.

throws Throwable

                public function average(string $sql): int|float|string|null;

            
batch() public abstract method

Starts a batch query.

A batch query supports fetching data in batches, which can keep the memory usage under a limit.

This method will return a Yiisoft\Db\Query\BatchQueryResultInterface object which implements the Iterator interface and can be traversed to retrieve the data in batches.

For example,

$query = (new Query)->from('user');

foreach ($query->batch() as $rows) {
    // $rows is an array of 100 or fewer rows from user table
}
public abstract batch( integer $batchSize 100 ): Yiisoft\Db\Query\BatchQueryResultInterface
$batchSize integer

The number of records to fetch in each batch.

return Yiisoft\Db\Query\BatchQueryResultInterface

The batch query result. It implements the Iterator interface and can be traversed to retrieve the data in batches.

                public function batch(int $batchSize = 100): BatchQueryResultInterface;

            
column() public abstract method

Executes the query and returns the first column of the result.

public abstract column( ): array
return array

The first column of the query result. It returns an empty array if the query results in nothing.

throws Yiisoft\Db\Exception\Exception
throws Yiisoft\Db\Exception\InvalidConfigException
throws Yiisoft\Db\Exception\NotSupportedException
throws Throwable

                public function column(): array;

            
count() public abstract method

Defined in: Yiisoft\Db\Query\QueryFunctionsInterface::count()

Returns the number of records.

Note: Make sure you quote column names in the expression.

public abstract count( string $sql '*' ): integer|string
$sql string

The COUNT expression. Defaults to '*'.

return integer|string

Number of records. The result will be a string when value is higher than \Yiisoft\Db\Query\PHP_INT_MAX.

throws Yiisoft\Db\Exception\InvalidConfigException
throws Throwable
throws Yiisoft\Db\Exception\Exception

                public function count(string $sql = '*'): int|string;

            
createCommand() public abstract method

Creates a DB command to execute the query.

public abstract createCommand( ): Yiisoft\Db\Command\CommandInterface
return Yiisoft\Db\Command\CommandInterface

The created DB command instance.

throws Yiisoft\Db\Exception\Exception
throws Yiisoft\Db\Exception\InvalidConfigException

                public function createCommand(): CommandInterface;

            
distinct() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::distinct()

Sets the value indicating whether to SELECT DISTINCT or not.

public abstract distinct( boolean $value true ): Yiisoft\Db\Query\QueryInterface
$value boolean

Whether to SELECT DISTINCT or not.

                public function distinct(bool $value = true): static;

            
each() public abstract method

Creates data reader to retrieve data row by row.

For example,

$query = (new Query)->from('user');

foreach ($query->each() as $row) {
}
public abstract each( ): Yiisoft\Db\Query\DataReaderInterface
return Yiisoft\Db\Query\DataReaderInterface

The data reader. It implements the Iterator interface and can be traversed to retrieve each row of data.

                public function each(): DataReaderInterface;

            
emulateExecution() public abstract method

Sets whether to emulate query execution without actually executing a query.

When enabled, methods returning results such as one(), all(), or exists() will return empty or false values.

You should use this method in case your program logic requires that a query shouldn't return any results.

public abstract emulateExecution( boolean $value true ): Yiisoft\Db\Query\QueryInterface
$value boolean

Whether to emulate query execution.

                public function emulateExecution(bool $value = true): static;

            
exists() public abstract method

Returns a value indicating whether the query result has any row of data.

public abstract exists( ): boolean
return boolean

Whether the query result has any row of data.

throws Yiisoft\Db\Exception\Exception
throws Yiisoft\Db\Exception\InvalidConfigException
throws Throwable

                public function exists(): bool;

            
filterHaving() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::filterHaving()

Sets the HAVING part of the query but ignores Query::isEmpty().

This method is similar to having(). The main difference is that this method will remove \Yiisoft\Db\Query\Query::isEmpty(). As a result, this method is best suited for building query conditions based on filter values entered by users.

The following code shows the difference between this method and having():

// HAVING `age`=:age
$query->filterHaving(['name' => null, 'age' => 20]);
// HAVING `age`=:age
$query->having(['age' => 20]);
// HAVING `name` IS NULL AND `age`=:age
$query->having(['name' => null, 'age' => 20]);

Note that unlike having(), you can't pass binding parameters to this method.

See also:

public abstract filterHaving( array $condition ): Yiisoft\Db\Query\QueryInterface
$condition array

The conditions that should be in the HAVING part. See having() on how to specify this parameter.

throws Yiisoft\Db\Exception\NotSupportedException

If this query doesn't support filtering.

                public function filterHaving(array $condition): static;

            
filterWhere() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::filterWhere()

Sets the WHERE part of the query but ignores Query::isEmpty().

This method is similar to where().

The main difference is that this method will remove \Yiisoft\Db\Query\Query::isEmpty().

As a result, this method is best suited for building query conditions based on filter values entered by users.

The following code shows the difference between this method and where():

// WHERE `age`=:age
$query->filterWhere(['name' => null, 'age' => 20]);
// WHERE `age`=:age
$query->where(['age' => 20]);
// WHERE `name` IS NULL AND `age`=:age
$query->where(['name' => null, 'age' => 20]);

Note that unlike where(), you can't pass binding parameters to this method.

See also:

public abstract filterWhere( array $condition ): Yiisoft\Db\Query\QueryInterface
$condition array

The conditions that should be in the WHERE part. where() On how to specify this parameter.

throws Yiisoft\Db\Exception\NotSupportedException

If this query doesn't support filtering.

                public function filterWhere(array $condition): static;

            
for() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::for()

Sets the FOR part of the query.

See also:

public abstract for( array|string|null $value ): Yiisoft\Db\Query\QueryInterface
$value array|string|null

The value(s) to be set for the FOR part. This can be either a string (for example, 'UPDATE') or a list of strings (such as ['SHARE OF {{t1}}', 'UPDATE OF {{t2}}']) specifying one or several values. null means no FOR part.

throws LogicException

If FOR was set previously.

                public function for(string|array|null $value): static;

            
from() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::from()

Sets the FROM part of the query.

public abstract from( array|Yiisoft\Db\Expression\ExpressionInterface|string $tables ): Yiisoft\Db\Query\QueryInterface
$tables array|Yiisoft\Db\Expression\ExpressionInterface|string

The table(s) to select from. This can be either a string (for example, 'user') or an array (such as ['user', 'profile']) specifying one or several table names. Table names can contain schema prefixes (such as 'public.user') and/or table aliases (such as 'user u'). The method will automatically quote the table names unless it has some parenthesis (which means the table is given as a sub-query or DB expression). When the tables are specified as an array, you may also use the array keys as the table aliases (if a table doesn't need alias, don't use a string key). Use a Query object to represent a sub-query. In this case, the corresponding array key will be used as the alias for the sub-query. To specify the FROM part in plain SQL, you may pass an instance of Yiisoft\Db\Expression\ExpressionInterface. Here are some examples:

// SELECT * FROM  `user` `u`, `profile`;
$query = (new \Yiisoft\Db\Query\Query)->from(['u' => 'user', 'profile']);

// SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
$subQuery = (new \Yiisoft\Db\Query\Query)->from('user')->where(['active' => true])
$query = (new \Yiisoft\Db\Query\Query)->from(['activeusers' => $subQuery]);

// subQuery can also be a string with plain SQL wrapped in parentheses
// SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
$subQuery = "(SELECT * FROM `user` WHERE `active` = 1)";
$query = (new \Yiisoft\Db\Query\Query)->from(['activeusers' => $subQuery]);

                public function from(array|ExpressionInterface|string $tables): static;

            
getDistinct() public abstract method

public abstract getDistinct( ): boolean
return boolean

The "distinct" value.

                public function getDistinct(): bool;

            
getFor() public abstract method

public abstract getFor( ): string[]
return string[]

The "for" values.

                public function getFor(): array;

            
getFrom() public abstract method

public abstract getFrom( ): array
return array

The "from" value.

                public function getFrom(): array;

            
getGroupBy() public abstract method

public abstract getGroupBy( ): array
return array

The "group by" value.

                public function getGroupBy(): array;

            
getHaving() public abstract method

public abstract getHaving( ): array|Yiisoft\Db\Expression\ExpressionInterface|string|null
return array|Yiisoft\Db\Expression\ExpressionInterface|string|null

The "having" value.

                public function getHaving(): string|array|ExpressionInterface|null;

            
getIndexBy() public abstract method

public abstract getIndexBy( ): Closure|string|null
return Closure|string|null

The "index by" value.

                public function getIndexBy(): Closure|string|null;

            
getJoins() public abstract method

public abstract getJoins( ): array
return array

The "join" value.

The format is:

[
    ['INNER JOIN', 'table1', 'table1.id = table2.id'],
    ['LEFT JOIN', 'table3', 'table1.id = table3.id'],
]

                public function getJoins(): array;

            
getLimit() public abstract method

public abstract getLimit( ): Yiisoft\Db\Expression\ExpressionInterface|integer|null
return Yiisoft\Db\Expression\ExpressionInterface|integer|null

The "limit" value.

                public function getLimit(): ExpressionInterface|int|null;

            
getOffset() public abstract method

public abstract getOffset( ): Yiisoft\Db\Expression\ExpressionInterface|integer|null
return Yiisoft\Db\Expression\ExpressionInterface|integer|null

The "offset" value.

                public function getOffset(): ExpressionInterface|int|null;

            
getOrderBy() public abstract method

public abstract getOrderBy( ): array
return array

The "order by" value.

                public function getOrderBy(): array;

            
getParams() public abstract method

public abstract getParams( ): array
return array

The "params" value.

                public function getParams(): array;

            
getResultCallback() public abstract method

Returns the callback to be called on all rows of the query result.

null will be returned if the callback is not set.

public abstract getResultCallback( ): Closure|null

                public function getResultCallback(): ?Closure;

            
getSelect() public abstract method

public abstract getSelect( ): array
return array

The "select" value.

                public function getSelect(): array;

            
getSelectOption() public abstract method

public abstract getSelectOption( ): string|null
return string|null

The "select option" value.

                public function getSelectOption(): ?string;

            
getTablesUsedInFrom() public abstract method

Returns table names used in from() indexed by aliases.

Both aliases and names are enclosed into {{ and }}.

public abstract getTablesUsedInFrom( ): array
return array

The table names indexed by aliases.

throws InvalidArgumentException

                public function getTablesUsedInFrom(): array;

            
getUnions() public abstract method

public abstract getUnions( ): array
return array

The "union" values.

The format is:

['SELECT * FROM table1', 'SELECT * FROM table2']

                public function getUnions(): array;

            
getWhere() public abstract method

public abstract getWhere( ): array|Yiisoft\Db\Expression\ExpressionInterface|string|null
return array|Yiisoft\Db\Expression\ExpressionInterface|string|null

The "where" value.

                public function getWhere(): array|string|ExpressionInterface|null;

            
getWithQueries() public abstract method

public abstract getWithQueries( ): Yiisoft\Db\Query\WithQuery[]
return Yiisoft\Db\Query\WithQuery[]

The "withQueries" value.

                public function getWithQueries(): array;

            
groupBy() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::groupBy()

Sets the GROUP BY part of the query.

See also addGroupBy().

public abstract groupBy( array|Yiisoft\Db\Expression\ExpressionInterface|string $columns ): Yiisoft\Db\Query\QueryInterface
$columns array|Yiisoft\Db\Expression\ExpressionInterface|string

The columns to be grouped by. Columns can be specified in either a string (for example "id, name") or an array (such as ['id', 'name']). The method will automatically quote the column names unless a column has some parenthesis (which means the column has a DB expression). Note that if your group-by is an expression containing commas, you should always use an array to represent the group-by information. Otherwise, the method won't be able to correctly decide the group-by columns.

Yiisoft\Db\Expression\ExpressionInterface object can be passed to specify the GROUP BY part explicitly in plain SQL. Yiisoft\Db\Expression\ExpressionInterface object can be passed as well.

                public function groupBy(array|string|ExpressionInterface $columns): static;

            
having() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::having()

Initially sets the HAVING part of the query.

See also:

public abstract having( array|Yiisoft\Db\Expression\ExpressionInterface|string|null $condition, array $params = [] ): Yiisoft\Db\Query\QueryInterface
$condition array|Yiisoft\Db\Expression\ExpressionInterface|string|null

The conditions to be put after HAVING. Please refer to where() on how to specify this parameter.

$params array

The parameters (name => value) to bind to the query.

throws LogicException

If having was set previously.

                public function having(array|ExpressionInterface|string|null $condition, array $params = []): static;

            
indexBy() public abstract method
public abstract indexBy( Closure|string|null $column ): Yiisoft\Db\Query\QueryInterface
$column Closure|string|null

The name of the column by which the query results should be indexed by. This can also be callable (for example, anonymous function) that returns the index value based on the given data. The signature of the callable should be:

function (array|object $data): int|string
{
    // return the index value corresponding to $data
}

                public function indexBy(string|Closure|null $column): static;

            
innerJoin() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::innerJoin()

Appends an INNER JOIN part to the query.

public abstract innerJoin( array|Yiisoft\Db\Expression\ExpressionInterface|string $table, array|Yiisoft\Db\Expression\ExpressionInterface|string $on '', array $params = [] ): Yiisoft\Db\Query\QueryInterface
$table array|Yiisoft\Db\Expression\ExpressionInterface|string

The table to be joined. Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (such as 'public.user') and/or table alias (such as 'user u'). The method will automatically quote the table name unless it has some parenthesis (which means the table is given as a sub-query or DB expression). Use an array to represent joining with a sub-query. The array must contain only one element. The value must be a Yiisoft\Db\Query\Query object representing the sub-query while the corresponding key represents the alias for the sub-query.

$on array|Yiisoft\Db\Expression\ExpressionInterface|string

The join condition that should appear in the ON part. Please refer to join() on how to specify this parameter.

$params array

The parameters (name => value) to bind to the query.

                public function innerJoin(
    array|ExpressionInterface|string $table,
    array|ExpressionInterface|string $on = '',
    array $params = [],
): static;

            
join() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::join()

Appends a JOIN part to the query.

The first parameter specifies what type of join it is.

public abstract join( string $type, array|Yiisoft\Db\Expression\ExpressionInterface|string $table, array|Yiisoft\Db\Expression\ExpressionInterface|string $on '', array $params = [] ): Yiisoft\Db\Query\QueryInterface
$type string

The type of join, such as INNER JOIN, LEFT JOIN.

$table array|Yiisoft\Db\Expression\ExpressionInterface|string

The table to join. Use a string to represent the name of the table to join. The table name can contain a schema prefix (such as 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it has some parenthesis (which means the table is given as a sub-query or DB expression). Use an array to represent joining with a sub-query. The array must contain only one element. The value must be a Yiisoft\Db\Query\Query object representing the sub-query while the corresponding key represents the alias for the sub-query.

$on array|Yiisoft\Db\Expression\ExpressionInterface|string

The join condition that should appear in the ON part. Please refer to where() on how to specify this parameter. Keys and values of an associative array are treated as column names and will be quoted before being used in an SQL query.

$params array

The parameters (name => value) to bind to the query.

                public function join(
    string $type,
    array|ExpressionInterface|string $table,
    array|ExpressionInterface|string $on = '',
    array $params = [],
): static;

            
leftJoin() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::leftJoin()

Appends a LEFT OUTER JOIN part to the query.

public abstract leftJoin( array|Yiisoft\Db\Expression\ExpressionInterface|string $table, array|Yiisoft\Db\Expression\ExpressionInterface|string $on '', array $params = [] ): Yiisoft\Db\Query\QueryInterface
$table array|Yiisoft\Db\Expression\ExpressionInterface|string

The table to join. Use a string to represent the name of the table to join. The table name can contain a schema prefix (such as 'public.user') and/or table alias (such as 'user u'). The method will automatically quote the table name unless it has some parenthesis (which means the table is given as a sub-query or DB expression). Use an array to represent joining with a sub-query. The array must contain only one element. The value must be a Yiisoft\Db\Query\Query object representing the sub-query while the corresponding key represents the alias for the sub-query.

$on array|Yiisoft\Db\Expression\ExpressionInterface|string

The join condition that should appear in the ON part. Please refer to join() on how to specify this parameter.

$params array

The parameters (name => value) to bind to the query.

                public function leftJoin(
    array|ExpressionInterface|string $table,
    array|ExpressionInterface|string $on = '',
    array $params = [],
): static;

            
limit() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::limit()

Sets the LIMIT part of the query.

public abstract limit( Yiisoft\Db\Expression\ExpressionInterface|integer|null $limit ): Yiisoft\Db\Query\QueryInterface
$limit Yiisoft\Db\Expression\ExpressionInterface|integer|null

The limit. Use null or negative value to disable limit.

                public function limit(ExpressionInterface|int|null $limit): static;

            
max() public abstract method

Defined in: Yiisoft\Db\Query\QueryFunctionsInterface::max()

Returns the maximum of the specified column values.

public abstract max( string $sql ): float|integer|string|null
$sql string

The column name or expression.

return float|integer|string|null

The maximum of the specified column values.

Note: Make sure you quote column names in the expression.

throws Yiisoft\Db\Exception\InvalidConfigException
throws Throwable
throws Yiisoft\Db\Exception\Exception

                public function max(string $sql): int|float|string|null;

            
min() public abstract method

Defined in: Yiisoft\Db\Query\QueryFunctionsInterface::min()

Returns the minimum of the specified column values.

public abstract min( string $sql ): float|integer|string|null
$sql string

The column name or expression.

return float|integer|string|null

The minimum of the specified column values.

Note: Make sure you quote column names in the expression.

throws Yiisoft\Db\Exception\InvalidConfigException
throws Throwable
throws Yiisoft\Db\Exception\Exception

                public function min(string $sql): int|float|string|null;

            
offset() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::offset()

Sets the OFFSET part of the query.

public abstract offset( Yiisoft\Db\Expression\ExpressionInterface|integer|null $offset ): Yiisoft\Db\Query\QueryInterface
$offset Yiisoft\Db\Expression\ExpressionInterface|integer|null

$offset The offset. Use null or negative value to disable offset.

                public function offset(ExpressionInterface|int|null $offset): static;

            
one() public abstract method

Executes the query and returns a single row of a result.

public abstract one( ): array|object|null
return array|object|null

The first row as an array or as an object of the query result. null if the query results in nothing.

throws Yiisoft\Db\Exception\Exception
throws Yiisoft\Db\Exception\InvalidConfigException
throws Throwable

                public function one(): array|object|null;

            
orFilterHaving() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::orFilterHaving()

Adds HAVING condition to the existing one but ignores Query::isEmpty().

The new condition and the existing one will be joined using the OR operator.

This method is similar to orHaving(). The main difference is that this method will remove \Yiisoft\Db\Query\Query::isEmpty(). As a result, this method is best suited for building query conditions based on filter values entered by users.

See also:

public abstract orFilterHaving( array $condition ): Yiisoft\Db\Query\QueryInterface
$condition array

The new HAVING condition. Please refer to having() on how to specify this parameter.

throws Yiisoft\Db\Exception\NotSupportedException

                public function orFilterHaving(array $condition): static;

            
orFilterWhere() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::orFilterWhere()

Adds WHERE condition to the existing one but ignores Query::isEmpty().

The new condition and the existing one will be joined using the 'OR' operator.

This method is similar to orWhere(). The main difference is that this method will remove \Yiisoft\Db\Query\Query::isEmpty(). As a result, this method is best suited for building query conditions based on filter values entered by users.

See also:

public abstract orFilterWhere( array $condition ): Yiisoft\Db\Query\QueryInterface
$condition array

The new WHERE condition. Please refer to where() on how to specify this parameter.

throws Yiisoft\Db\Exception\NotSupportedException

                public function orFilterWhere(array $condition): static;

            
orHaving() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::orHaving()

Adds HAVING condition to the existing one.

The new condition and the existing one will be joined using the OR operator.

See also:

public abstract orHaving( array|Yiisoft\Db\Expression\ExpressionInterface|string $condition, array $params = [] ): Yiisoft\Db\Query\QueryInterface
$condition array|Yiisoft\Db\Expression\ExpressionInterface|string

The new HAVING condition. Please refer to where() on how to specify this parameter.

$params array

The parameters (name => value) to bind to the query.

                public function orHaving(array|string|ExpressionInterface $condition, array $params = []): static;

            
orWhere() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::orWhere()

Adds WHERE condition to the existing one.

The new condition and the existing one will be joined using the OR operator.

See also:

public abstract orWhere( array|Yiisoft\Db\Expression\ExpressionInterface|string $condition, array $params = [] ): Yiisoft\Db\Query\QueryInterface
$condition array|Yiisoft\Db\Expression\ExpressionInterface|string

The new WHERE condition. Please refer to where() on how to specify this parameter.

$params array

The parameters (name => value) to bind to the query.

                public function orWhere(array|string|ExpressionInterface $condition, array $params = []): static;

            
orderBy() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::orderBy()

Sets the ORDER BY part of the query.

See also addOrderBy().

public abstract orderBy( array|Yiisoft\Db\Expression\ExpressionInterface|string $columns ): Yiisoft\Db\Query\QueryInterface
$columns array|Yiisoft\Db\Expression\ExpressionInterface|string

The columns (and the directions) to be ordered by. Columns can be specified in either a string (for example "id ASC, name DESC") or an array (such as ['id' => SORT_ASC, 'name' => SORT_DESC]). The method will automatically quote the column names unless a column has some parenthesis (which means the column has a DB expression). Note that if your order-by is an expression containing commas, you should always use an array to represent the order-by information. Otherwise, the method won't be able to correctly decide the order-by columns. Since Yiisoft\Db\Expression\ExpressionInterface an object can be passed to specify the ORDER BY part explicitly in plain SQL.

                public function orderBy(array|string|ExpressionInterface $columns): static;

            
params() public abstract method

Sets the parameters to bind to the query.

See also addParams().

public abstract params( array $params ): Yiisoft\Db\Query\QueryInterface
$params array

List of query parameter values indexed by parameter placeholders. For example, [':name' => 'Dan', ':age' => 31].

                public function params(array $params): static;

            
prepare() public abstract method

Prepare for building SQL.

Yiisoft\Db\QueryBuilder\QueryBuilderInterface uses this method when it starts to build SQL from a query object. You may override this method to do some final preparation work when converting a query into an SQL statement.

public abstract prepare( Yiisoft\Db\QueryBuilder\QueryBuilderInterface $builder ): self
$builder Yiisoft\Db\QueryBuilder\QueryBuilderInterface

The query builder.

                public function prepare(QueryBuilderInterface $builder): self;

            
resultCallback() public abstract method

Sets the callback, to be called on all rows of the query result before returning them.

For example:

$users = $db->createQuery()
    ->from('user')
    ->resultCallback(function (array $rows): array {
        foreach ($rows as &$row) {
            $row['name'] = strtoupper($row['name']);
        }
        return $rows;
    })
    ->all();
public abstract resultCallback( Closure|null $resultCallback ): Yiisoft\Db\Query\QueryInterface
$resultCallback Closure|null

                public function resultCallback(?Closure $resultCallback): static;

            
rightJoin() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::rightJoin()

Appends a RIGHT OUTER JOIN part to the query.

public abstract rightJoin( array|Yiisoft\Db\Expression\ExpressionInterface|string $table, array|Yiisoft\Db\Expression\ExpressionInterface|string $on '', array $params = [] ): Yiisoft\Db\Query\QueryInterface
$table array|Yiisoft\Db\Expression\ExpressionInterface|string

The table to be joined. Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (such as public.user) and/or table alias (such as user u). The method will automatically quote the table name unless it has some parenthesis (which means the table is given as a sub-query or DB expression). Use an array to represent joining with a sub-query. The array must contain only one element. The value must be a Yiisoft\Db\Query\Query object representing the sub-query while the corresponding key represents the alias for the sub-query.

$on array|Yiisoft\Db\Expression\ExpressionInterface|string

The join condition that should appear in the ON part. Please refer to join() on how to specify this parameter.

$params array

The parameters (name => value) to be bound to the query.

                public function rightJoin(
    array|ExpressionInterface|string $table,
    array|ExpressionInterface|string $on = '',
    array $params = [],
): static;

            
scalar() public abstract method

Returns the query results as a scalar value.

The value returned will be the first column in the first row of the query results. Do not use this method for boolean values as it returns false if the query result is empty.

public abstract scalar( ): boolean|float|integer|string|null
return boolean|float|integer|string|null

The value of the first column in the first row of the query result. False is returned if the query result is empty.

throws Yiisoft\Db\Exception\Exception
throws Yiisoft\Db\Exception\InvalidConfigException
throws Throwable

                public function scalar(): bool|int|string|float|null;

            
select() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::select()

Sets the SELECT part of the query.

public abstract select( array|Yiisoft\Db\Expression\ExpressionInterface|scalar $columns, string|null $option null ): Yiisoft\Db\Query\QueryInterface
$columns array|Yiisoft\Db\Expression\ExpressionInterface|scalar

The columns to be selected. Columns can be specified in either a string (for example id, name) or an array (such as ['id', 'name']). Columns can be prefixed with table names (such as user.id) and/or contain column aliases (for example user.id AS user_id). The method will automatically quote the column names unless a column has some parenthesis (which means the column has a DB expression). A DB expression may also be passed in form of an Yiisoft\Db\Expression\ExpressionInterface object. Note that if you are selecting an expression like CONCAT(first_name, ' ', last_name), you should use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts. When the columns are specified as an array, you may also use array keys as the column aliases (if a column doesn't need alias, don't use a string key).

$option string|null

More option that should be appended to the 'SELECT' keyword. For example, in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.

Version Description
2.0.0 `$columns` can be a scalar value or an array of scalar values. For example, `$query->select(1)` will be converted to `SELECT 1`.

                public function select(array|bool|float|int|string|ExpressionInterface $columns, ?string $option = null): static;

            
selectOption() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::selectOption()

It allows you to specify more options for the SELECT clause of an SQL statement.

public abstract selectOption( string|null $value ): Yiisoft\Db\Query\QueryInterface
$value string|null

More option that should be appended to the 'SELECT' keyword. For example, in MySQL, the option SQL_CALC_FOUND_ROWS can be used.

                public function selectOption(?string $value): static;

            
setFor() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::setFor()

Overwrites the FOR part of the query.

See also:

public abstract setFor( array|string|null $value ): Yiisoft\Db\Query\QueryInterface
$value array|string|null

The value(s) to be set for the FOR part. This can be either a string (for example, 'UPDATE') or a list of strings (such as ['SHARE OF {{t1}}', 'UPDATE OF {{t2}}']) specifying one or several values. null means no FOR part.

                public function setFor(string|array|null $value): static;

            
setHaving() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::setHaving()

Overwrites the HAVING part of the query.

See also having().

public abstract setHaving( array|Yiisoft\Db\Expression\ExpressionInterface|string|null $condition, array $params = [] ): Yiisoft\Db\Query\QueryInterface
$condition array|Yiisoft\Db\Expression\ExpressionInterface|string|null

The conditions to be put after HAVING.

$params array

The parameters (name => value) to bind to the query.

                public function setHaving(array|ExpressionInterface|string|null $condition, array $params = []): static;

            
setJoins() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::setJoins()

Specify the joins for a SELECT statement in a database query.

public abstract setJoins( array $value ): Yiisoft\Db\Query\QueryInterface
$value array

The joins to perform in the query. The format is the following:

[
    ['INNER JOIN', 'table1', 'table1.id = table2.id'],
    ['LEFT JOIN', 'table3', 'table1.id = table3.id'],
]

                public function setJoins(array $value): static;

            
setUnions() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::setUnions()

Specify queries for a SELECT statement that are combined with UNIONs.

public abstract setUnions( array $value ): Yiisoft\Db\Query\QueryInterface
$value array

The queries to union such as ['SELECT * FROM table1', 'SELECT * FROM table2'].

                public function setUnions(array $value): static;

            
setWhere() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::setWhere()

Overwrites the WHERE part of the query.

See also where().

public abstract setWhere( array|Yiisoft\Db\Expression\ExpressionInterface|string|null $condition, array $params = [] ): Yiisoft\Db\Query\QueryInterface
$condition array|Yiisoft\Db\Expression\ExpressionInterface|string|null

The conditions to put in the WHERE part.

$params array

The parameters (name => value) to bind to the query.

                public function setWhere(array|string|ExpressionInterface|null $condition, array $params = []): static;

            
shouldEmulateExecution() public abstract method

public abstract shouldEmulateExecution( ): boolean
return boolean

Whether to emulate query execution.

                public function shouldEmulateExecution(): bool;

            
sum() public abstract method

Defined in: Yiisoft\Db\Query\QueryFunctionsInterface::sum()

Returns the sum of the specified column values.

public abstract sum( string $sql ): float|integer|string|null
$sql string

The column name or expression.

return float|integer|string|null

The sum of the specified column values.

Note: Make sure you quote column names in the expression.

throws Yiisoft\Db\Exception\InvalidConfigException
throws Throwable
throws Yiisoft\Db\Exception\Exception

                public function sum(string $sql): int|float|string|null;

            
union() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::union()

Appends an SQL statement using UNION operator.

public abstract union( Yiisoft\Db\Query\QueryInterface|string $sql, boolean $all false ): Yiisoft\Db\Query\QueryInterface
$sql Yiisoft\Db\Query\QueryInterface|string

$sql The SQL statement to be appended using UNION.

$all boolean

true if using UNION ALL and false if using UNION.

                public function union(QueryInterface|string $sql, bool $all = false): static;

            
where() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::where()

Initially sets the WHERE part of the query.

The $condition specified as an array can be in one of the following two formats:

  • key-value format: ['column1' => value1, 'column2' => value2, ...]
  • operator format: [operator, operand1, operand2, ...]

A condition in key-value format represents the following SQL expression in general: column1=value1 AND column2=value2 AND .... In case when a value is an array, an IN expression will be generated. And if a value is null, IS NULL will be used in the generated expression. Below are some examples:

  • ['type' => 1, 'status' => 2] generates (type = 1) AND (status = 2).
  • ['id' => [1, 2, 3], 'status' => 2] generates (id IN (1, 2, 3)) AND (status = 2).
  • ['status' => null] generates status IS NULL.

A condition in operator format generates the SQL expression according to the specified operator, which can be one of the following:

  • and: the operands should be concatenated together using AND. For example, ['and', 'id=1', 'id=2'] will generate id=1 AND id=2. If an operand is an array, it will be converted into a string using the rules described here. For example, ['and', 'type=1', ['or', 'id=1', 'id=2']] will generate type=1 AND (id=1 OR id=2). The method will not do any quoting or escaping.

  • or: similar to the and operator except that the operands are concatenated using OR. For example, ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]] will generate (type IN (7, 8, 9) OR (id IN (1, 2, 3))).

  • not: this will take only one operand and build the negation of it by prefixing the query string with NOT. For example ['not', ['attribute' => null]] will result in the condition NOT (attribute IS NULL).

  • between: operand 1 should be the column name, and operand 2 and 3 should be the starting and ending values of the range that the column is in. For example, ['between', 'id', 1, 10] will generate id BETWEEN 1 AND 10.

  • not between: similar to between except the BETWEEN is replaced with NOT BETWEEN in the generated condition.

  • in: operand 1 should be a column or DB expression, and operand 2 be an array representing the range of the values that the column or DB expression should be in. For example, ['in', 'id', [1, 2, 3]] will generate id IN (1, 2, 3). The method will quote the column name and escape values in the range.

    To create a composite IN condition you can use and array for the column name and value, where the values are indexed by the column name: ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']] ].

    You may also specify a sub-query that's used to get the values for the IN-condition: ['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]

  • not in: similar to the in operator except that IN is replaced with NOT IN in the generated condition.

  • like: operand 1 should be a column or DB expression, and operand 2 be a string or an array representing the values that the column or DB expression should be like. For example, ['like', 'name', 'tester'] will generate name LIKE '%tester%'. When the value range is given as an array, many LIKE predicates will be generated and concatenated using AND. For example, ['like', 'name', ['test', 'sample']] will generate name LIKE '%test%' AND name LIKE '%sample%'. The method will quote the column name and escape special characters in the values. Sometimes, you may want to add the percentage characters to the matching value by yourself. You may supply a third operand false to do so. For example, ['like', 'name', '%tester', false] will generate name LIKE '%tester'.

  • or like: similar to the like operator except that OR is used to concatenate the LIKE predicates when operand 2 is an array.

  • not like: similar to the like operator except that LIKE is replaced with NOT LIKE in the generated condition.

  • or not like: similar to the not like operator except that OR is used to concatenate the NOT LIKE predicates.

  • exists: operand 1 is a query object that used to build an EXISTS condition. For example ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])] will result in the following SQL expression: EXISTS (SELECT "id" FROM "users" WHERE "active"=1).

  • not exists: similar to the exists operator except that EXISTS is replaced with NOT EXISTS in the generated condition.

  • Additionally, you can specify arbitrary operators as follows: A condition of ['>=', 'id', 10] will result in the following SQL expression: id >= 10.

Note that this method will override any existing WHERE condition. You might want to use andWhere() or orWhere() instead.

See also:

public abstract where( array|Yiisoft\Db\Expression\ExpressionInterface|string|null $condition, array $params = [] ): Yiisoft\Db\Query\QueryInterface
$condition array|Yiisoft\Db\Expression\ExpressionInterface|string|null

The conditions to put in the WHERE part.

$params array

The parameters (name => value) to bind to the query.

throws LogicException

If where was set previously.

                public function where(array|string|ExpressionInterface|null $condition, array $params = []): static;

            
withQueries() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::withQueries()

Specifies the WITH query clause for the query.

public abstract withQueries( Yiisoft\Db\Query\WithQuery $queries ): Yiisoft\Db\Query\QueryInterface
$queries Yiisoft\Db\Query\WithQuery

The WITH queries to append to the query.

                public function withQueries(WithQuery ...$queries): static;

            
withQuery() public abstract method

Defined in: Yiisoft\Db\Query\QueryPartsInterface::withQuery()

Set an SQL statement using WITH syntax.

public abstract withQuery( Yiisoft\Db\Query\QueryInterface|string $query, Yiisoft\Db\Expression\ExpressionInterface|string $alias, boolean $recursive false ): Yiisoft\Db\Query\QueryInterface
$query Yiisoft\Db\Query\QueryInterface|string

The SQL statement.

$alias Yiisoft\Db\Expression\ExpressionInterface|string

The query alias in WITH construction. To specify the alias in plain SQL, you may pass an instance of Yiisoft\Db\Expression\ExpressionInterface.

$recursive boolean

Its true if using WITH RECURSIVE and false if using WITH.

                public function withQuery(
    QueryInterface|string $query,
    ExpressionInterface|string $alias,
    bool $recursive = false,
): static;

            
withTypecasting() public abstract method

Returns a copy of the instance with enabled or disabled typecasting of values when retrieving records from DB.

public abstract withTypecasting( boolean $typecasting true ): Yiisoft\Db\Query\QueryInterface
$typecasting boolean

                public function withTypecasting(bool $typecasting = true): static;