Skip to content
PHP Ecosystem
Explore

Query

API reference › yii › db › Query

1 subclass

Query represents a SELECT SQL statement in a way that is independent of DBMS.

Query provides a set of methods to facilitate the specification of different clauses in a SELECT statement. These methods can be chained together.

By calling createCommand(), we can get a Command instance which can be further used to perform/execute the DB query against a database.

For example,

$query = new Query;
// compose the query
$query->select('id, name')
->from('user')
->limit(10);
// build and execute the query
$rows = $query->all();
// alternatively, you can create DB command and execute it
$command = $query->createCommand();
// $command->sql returns the actual SQL
$rows = $command->queryAll();

Query internally uses the QueryBuilder class to generate the SQL statement.

A more detailed usage guide on how to work with Query can be found in the guide article on Query Builder.

PropertyTypeDescriptionDefined by
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$distinctboolWhether to select distinct rows of data only. Default: false.Query
$emulateExecutionboolWhether to emulate the actual query execution, returning empty or false results. Default: false. Available since 2.0.11.QueryTrait
$fromarray|string|nullThe table(s) to be selected from. Default: null.Query
$groupByarray|nullHow to group the query results. Default: null.Query
$havingstring|array|ExpressionInterface|nullThe condition to be applied in the GROUP BY clause. Default: null.Query
$indexBystring|callable|nullThe name of the column by which the query results should be indexed by. Default: null.QueryTrait
$joinarray|nullHow to join with other tables. Default: null.Query
$limitint|ExpressionInterface|nullMaximum number of records to be returned. Default: null.QueryTrait
$offsetint|ExpressionInterface|nullZero-based offset from where the records are to be returned. Default: null.QueryTrait
$orderByarray|nullHow to sort the query results. Default: null.QueryTrait
$paramsarray|nullList of query parameter values indexed by parameter placeholders. Default: [].Query
$queryCacheDependencyyii\caching\Dependency|nullThe dependency to be associated with the cached query result for this query Default: null. Available since 2.0.14.Query
$queryCacheDurationint|bool|nullThe default number of seconds that query results can remain valid in cache. Default: null. Available since 2.0.14.Query
$selectarray|nullThe columns being selected. Default: null.Query
$selectOptionstring|nullAdditional option that should be appended to the ‘SELECT’ keyword. Default: null.Query
$tablesUsedInFrom read-onlystring[]Table names indexed by aliases.Query
$unionarray|nullThis is used to construct the UNION clause(s) in a SQL statement. Default: null.Query
$unionLimitint|ExpressionInterface|nullNumber of records to return from the complete UNION result. Default: null. Available since 22.0.Query
$unionOffsetint|ExpressionInterface|nullZero-based offset for the complete UNION result. Default: null. Available since 22.0.Query
$unionOrderByarray<int|string, int|ExpressionInterface>|nullHow to sort the complete UNION result. Default: null. Available since 22.0.Query
$wherestring|array|ExpressionInterface|nullQuery condition. Default: null.QueryTrait
$withQueriesarray|nullThis is used to construct the WITH section in a SQL query. Default: null. Available since 2.0.35.Query
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__toString()Returns the SQL representation of QueryQuery
__unset()Sets a component property to be null.yii\base\Component
addGroupBy()Adds additional group-by columns to the existing ones.Query
addOrderBy()Adds additional ORDER BY columns to the query.QueryTrait
addParams()Adds additional parameters to be bound to the query.Query
addSelect()Add more columns to the SELECT part of the query.Query
addUnionOrderBy()Adds ORDER BY columns to the complete UNION result.Query
all()Executes the query and returns all results as an array.Query
andFilterCompare()Adds a filtering condition for a specific column and allow the user to choose a filter operator.Query
andFilterHaving()Adds an additional HAVING condition to the existing one but ignores empty operands.Query
andFilterWhere()Adds an additional WHERE condition to the existing one but ignores empty operands.QueryTrait
andHaving()Adds an additional HAVING condition to the existing one.Query
andWhere()Adds an additional WHERE condition to the existing one.Query
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
average()Returns the average of the specified column values.Query
batch()Starts a batch query.Query
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
cache()Enables query cache for this Query.Query
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
column()Executes the query and returns the first column of the result.Query
count()Returns the number of records.Query
create() staticCreates a new Query object and copies its property values from an existing one.Query
createCommand()Creates a DB command that can be used to execute this query.Query
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
distinct()Sets the value indicating whether to SELECT DISTINCT or not.Query
each()Starts a batch query and retrieves data row by row.Query
emulateExecution()Sets whether to emulate query execution, preventing any interaction with data storage.QueryTrait
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
exists()Returns a value indicating whether the query result contains any row of data.Query
filterHaving()Sets the HAVING part of the query but ignores empty operands.Query
filterWhere()Sets the WHERE part of the query but ignores empty operands.QueryTrait
from()Sets the FROM part of the query.Query
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getTablesUsedInFrom()Returns table names used in from() indexed by aliases.Query
groupBy()Sets the GROUP BY part of the query.Query
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
having()Sets the HAVING part of the query.Query
indexBy()Sets the indexBy() property.QueryTrait
init()Initializes the object.yii\base\BaseObject
innerJoin()Appends an INNER JOIN part to the query.Query
join()Appends a JOIN part to the query.Query
leftJoin()Appends a LEFT OUTER JOIN part to the query.Query
limit()Sets the LIMIT part of the query.QueryTrait
max()Returns the maximum of the specified column values.Query
min()Returns the minimum of the specified column values.Query
noCache()Disables query cache for this Query.Query
off()Detaches an existing event handler from this component.yii\base\Component
offset()Sets the OFFSET part of the query.QueryTrait
on()Attaches an event handler to an event.yii\base\Component
one()Executes the query and returns a single row of result.Query
orderBy()Sets the ORDER BY part of the query.QueryTrait
orFilterHaving()Adds an additional HAVING condition to the existing one but ignores empty operands.Query
orFilterWhere()Adds an additional WHERE condition to the existing one but ignores empty operands.QueryTrait
orHaving()Adds an additional HAVING condition to the existing one.Query
orWhere()Adds an additional WHERE condition to the existing one.Query
params()Sets the parameters to be bound to the query.Query
populate()Converts the raw query results into the format as specified by this query.Query
prepare()Prepares for building SQL.Query
rightJoin()Appends a RIGHT OUTER JOIN part to the query.Query
scalar()Returns the query result as a scalar value.Query
select()Sets the SELECT part of the query.Query
sum()Returns the sum of the specified column values.Query
trigger()Triggers an event.yii\base\Component
union()Appends a SQL statement using UNION operator.Query
unionLimit()Sets the LIMIT part of the complete UNION result.Query
unionOffset()Sets the OFFSET part of the complete UNION result.Query
unionOrderBy()Sets the ORDER BY part of the complete UNION result.Query
where()Sets the WHERE part of the query.Query
withQuery()Prepends a SQL statement using WITH syntax.Query
cleanUpTableNames() protectedClean up table names and aliases Both aliases and names are enclosed into {{ and }}.Query
filterCondition() protectedRemoves empty operands from the given query condition.QueryTrait
isEmpty() protectedReturns a value indicating whether the give value is “empty”.QueryTrait
normalizeOrderBy() protectedNormalizes format of ORDER BY data.QueryTrait
normalizeSelect() protectedNormalizes the SELECT columns passed to select() or addSelect().Query
queryScalar() protectedQueries a scalar value by setting select() first.Query
setCommandCache() protectedSets $command cache, if this query has enabled caching.Query
public bool $distinct = false

Whether to select distinct rows of data only.

If this is set true, the SELECT clause would be changed to SELECT DISTINCT.

public array|string|null $from = null

The table(s) to be selected from.

For example, ['user', 'post']. This is used to construct the FROM clause in a SQL statement.

public array|null $groupBy = null

How to group the query results.

For example, ['company', 'department']. This is used to construct the GROUP BY clause in a SQL statement.

public string|array|yii\db\ExpressionInterface|null $having = null

The condition to be applied in the GROUP BY clause.

It can be either a string or an array. Please refer to where() on how to specify the condition.

public array|null $join = null

How to join with other tables.

Each array element represents the specification of one join which has the following structure:

[$joinType, $tableName, $joinCondition]

For example,

[
['INNER JOIN', 'user', 'user.id = author_id'],
['LEFT JOIN', 'team', 'team.id = team_id'],
]
public array|null $params = []

List of query parameter values indexed by parameter placeholders.

For example, [':name' => 'Dan', ':age' => 31].

public int|bool|null $queryCacheDuration = null

The default number of seconds that query results can remain valid in cache.

Use 0 to indicate that the cached data will never expire. Use a negative number to indicate that query cache should not be used. Use boolean true to indicate that Connection::$queryCacheDuration should be used.

Since

2.0.14

public array|null $select = null

The columns being selected.

For example, ['id', 'name']. This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.

public string|null $selectOption = null

Additional option that should be appended to the ‘SELECT’ keyword.

For example, in MySQL, the option ‘SQL_CALC_FOUND_ROWS’ can be used.

public array|null $union = null

This is used to construct the UNION clause(s) in a SQL statement.

Each array element is an array of the following structure:

  • query: either a string or a Query object representing a query
  • all: boolean, whether it should be UNION ALL or UNION
public array|null $withQueries = null

This is used to construct the WITH section in a SQL query.

Each array element is an array of the following structure:

  • query: either a string or a Query object representing a query
  • alias: string, alias of query for further usage
  • recursive: boolean, whether it should be WITH RECURSIVE or WITH

Since

2.0.35

public function __toString(): string

Returns the SQL representation of Query

Returns

string

public function addGroupBy(string|array|yii\db\ExpressionInterface $columns): $this

Adds additional group-by columns to the existing ones.

Parameters

ParameterTypeDescription
$columnsstring|array|ExpressionInterfaceAdditional columns to be grouped by. Columns can be specified in either a string (e.g. “id, name”) or an array (e.g. [‘id’, ‘name’]). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains 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 will not be able to correctly determine the group-by columns. Since version 2.0.7, an Expression object can be passed to specify the GROUP BY part explicitly in plain SQL. Since version 2.0.14, an ExpressionInterface object can be passed as well.

Returns

$this: The query object itself

See also

public function addParams(array $params): $this

Adds additional parameters to be bound to the query.

Parameters

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

Returns

$this: The query object itself

See also

public function addSelect(string|array|yii\db\ExpressionInterface $columns): $this

Add more columns to the SELECT part of the query.

Note, that if select() has not 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();

Parameters

ParameterTypeDescription
$columnsstring|array|ExpressionInterfaceThe columns to add to the select. See select() for more details about the format of this parameter.

Returns

$this: The query object itself

See also

public function addUnionOrderBy(array<int|string, int|yii\db\ExpressionInterface>|string|yii\db\ExpressionInterface|null $columns): static

Adds ORDER BY columns to the complete UNION result.

Parameters

ParameterTypeDescription
$columnsarray<int|string, int|ExpressionInterface>|string|ExpressionInterface|nullThe columns (and the directions) to be ordered by.

Returns

static: The query object itself.

Since

22.0

See also

public function all(yii\db\Connection|null $db = null): array

Executes the query and returns all results as an array.

Parameters

ParameterTypeDescription
$dbConnection|nullThe database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.

Returns

array: The query results. If the query results in nothing, an empty array will be returned.

public function andFilterCompare(string $name, string $value, string $defaultOperator = '='): $this

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

It adds an additional 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 empty values are ignored. The new condition and the existing one will be 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 none of the above operators is detected, the $defaultOperator will be used.

Parameters

ParameterTypeDescription
$namestringThe column name.
$valuestringThe column value optionally prepended with the comparison operator.
$defaultOperatorstringThe operator to use, when no operator is given in $value. Defaults to =, performing an exact match.

Returns

$this: The query object itself

Since

2.0.8

public function andFilterHaving(array $condition): $this

Adds an additional HAVING condition to the existing one but ignores empty operands.

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 empty query operands. As a result, this method is best suited for building query conditions based on filter values entered by users.

Parameters

ParameterTypeDescription
$conditionarrayThe new HAVING condition. Please refer to having() on how to specify this parameter.

Returns

$this: The query object itself

Since

2.0.11

See also

public function andHaving(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this

Adds an additional HAVING condition to the existing one.

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

Parameters

ParameterTypeDescription
$conditionstring|array|ExpressionInterfaceThe new HAVING condition. Please refer to where() on how to specify this parameter.
$paramsarrayThe parameters (name => value) to be bound to the query.

Returns

$this: The query object itself

See also

public function andWhere(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this

Adds an additional WHERE condition to the existing one.

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

Parameters

ParameterTypeDescription
$conditionstring|array|ExpressionInterfaceThe new WHERE condition. Please refer to where() on how to specify this parameter.
$paramsarrayThe parameters (name => value) to be bound to the query.

Returns

$this: The query object itself

See also

public function average(string $q, yii\db\Connection|null $db = null): mixed

Returns the average of the specified column values.

Parameters

ParameterTypeDescription
$qstringThe column name or expression. Make sure you properly quote column names in the expression.
$dbConnection|nullThe database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.

Returns

mixed: The average of the specified column values.

public function batch(int $batchSize = 100, yii\db\Connection|null $db = null): yii\db\BatchQueryResult

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 BatchQueryResult 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
}

Parameters

ParameterTypeDescription
$batchSizeintThe number of records to be fetched in each batch.
$dbConnection|nullThe database connection. If not set, the “db” application component will be used.

Returns

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

public function cache(int|true $duration = true, yii\caching\Dependency|null $dependency = null): $this

Enables query cache for this Query.

Parameters

ParameterTypeDescription
$durationint|trueThe number of seconds that query results can remain valid in cache. Use 0 to indicate that the cached data will never expire. Use a negative number to indicate that query cache should not be used. Use boolean true to indicate that Connection::$queryCacheDuration should be used. Defaults to true.
$dependencyyii\caching\Dependency|nullThe cache dependency associated with the cached result.

Returns

$this: The Query object itself

Since

2.0.14

public function column(yii\db\Connection|null $db = null): array

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

Parameters

ParameterTypeDescription
$dbConnection|nullThe database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.

Returns

array: The first column of the query result. An empty array is returned if the query results in nothing.

public function count(string $q = '*', yii\db\Connection|null $db = null): int|string|null

Returns the number of records.

Parameters

ParameterTypeDescription
$qstringThe COUNT expression. Defaults to ’*’. Make sure you properly quote column names in the expression.
$dbConnection|nullThe database connection used to generate the SQL statement. If this parameter is not given (or null), the db application component will be used.

Returns

int|string|null: Number of records. The result may be a string depending on the underlying database engine and to support integer values higher than a 32bit PHP integer can handle.

public static function create(yii\db\Query $from): yii\db\Query

Creates a new Query object and copies its property values from an existing one.

The properties being copies are the ones to be used by query builders.

Parameters

ParameterTypeDescription
$fromQueryThe source query object

Returns

Query: The new Query object

public function createCommand(yii\db\Connection|null $db = null): yii\db\Command

Creates a DB command that can be used to execute this query.

Parameters

ParameterTypeDescription
$dbConnection|nullThe database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.

Returns

Command: The created DB command instance.

public function distinct(bool $value = true): $this

Sets the value indicating whether to SELECT DISTINCT or not.

Parameters

ParameterTypeDescription
$valueboolWhether to SELECT DISTINCT or not.

Returns

$this: The query object itself

public function each(int $batchSize = 100, yii\db\Connection|null $db = null): yii\db\BatchQueryResult

Starts a batch query and retrieves data row by row.

This method is similar to batch() except that in each iteration of the result, only one row of data is returned. For example,

$query = (new Query)->from('user');
foreach ($query->each() as $row) {
}

Parameters

ParameterTypeDescription
$batchSizeintThe number of records to be fetched in each batch.
$dbConnection|nullThe database connection. If not set, the “db” application component will be used.

Returns

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

public function exists(yii\db\Connection|null $db = null): bool

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

Parameters

ParameterTypeDescription
$dbConnection|nullThe database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.

Returns

bool: Whether the query result contains any row of data.

public function filterHaving(array $condition): $this

Sets the HAVING part of the query but ignores empty operands.

This method is similar to having(). The main difference is that this method will remove empty query operands. 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 cannot pass binding parameters to this method.

Parameters

ParameterTypeDescription
$conditionarrayThe conditions that should be put in the HAVING part. See having() on how to specify this parameter.

Returns

$this: The query object itself

Since

2.0.11

See also

public function from(string|array|yii\db\ExpressionInterface $tables): $this

Sets the FROM part of the query.

Parameters

ParameterTypeDescription
$tablesstring|array|ExpressionInterfaceThe table(s) to be selected from. This can be either a string (e.g. 'user') or an array (e.g. ['user', 'profile']) specifying one or several table names. Table names can contain schema prefixes (e.g. 'public.user') and/or table aliases (e.g. 'user u'). The method will automatically quote the table names unless it contains 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 does not need alias, do not 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 ExpressionInterface. Here are some examples: // SELECT * FROM user u, profile; $query = (new \yii\db\Query)->from([‘u’ => ‘user’, ‘profile’]); // SELECT * FROM (SELECT * FROM user WHERE active = 1) activeusers; $subquery = (new \yii\db\Query)->from(‘user’)->where([‘active’ => true]) $query = (new \yii\db\Query)->from([‘activeusers’ => $subquery]); // subquery can also be a string with plain SQL wrapped in parenthesis // SELECT * FROM (SELECT * FROM user WHERE active = 1) activeusers; $subquery = “(SELECT * FROM user WHERE active = 1)”; $query = (new \yii\db\Query)->from([‘activeusers’ => $subquery]);

Returns

$this: The query object itself

public function getTablesUsedInFrom(): string[]

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

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

Returns

string[]: Table names indexed by aliases

Throws

Since

2.0.12

public function groupBy(string|array|yii\db\ExpressionInterface|null $columns): $this

Sets the GROUP BY part of the query.

Parameters

ParameterTypeDescription
$columnsstring|array|ExpressionInterface|nullThe columns to be grouped by. Columns can be specified in either a string (e.g. “id, name”) or an array (e.g. [‘id’, ‘name’]). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains 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 will not be able to correctly determine the group-by columns. Since version 2.0.7, an ExpressionInterface object can be passed to specify the GROUP BY part explicitly in plain SQL. Since version 2.0.14, an ExpressionInterface object can be passed as well.

Returns

$this: The query object itself

See also

public function having(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this

Sets the HAVING part of the query.

Parameters

ParameterTypeDescription
$conditionstring|array|ExpressionInterfaceThe conditions to be put after HAVING. Please refer to where() on how to specify this parameter.
$paramsarrayThe parameters (name => value) to be bound to the query.

Returns

$this: The query object itself

See also

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

Appends an INNER JOIN part to the query.

Parameters

ParameterTypeDescription
$tablestring|arrayThe table or sub-query to be joined. Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. ‘public.user’) and/or table alias (e.g. ‘user u’). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression). You may also specify the table as an array with one element, using the array key as the table alias (e.g. [‘u’ => ‘user’]). To join a sub-query, use an array with one element, with the value set to a Query object representing the sub-query, and the corresponding key representing the alias.
$onstring|arrayThe join condition that should appear in the ON part. Please refer to join() on how to specify this parameter.
$paramsarrayThe parameters (name => value) to be bound to the query.

Returns

$this: The query object itself

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

Appends a JOIN part to the query.

The first parameter specifies what type of join it is.

Parameters

ParameterTypeDescription
$typestringThe type of join, such as INNER JOIN, LEFT JOIN.
$tablestring|arrayThe table or sub-query to be joined. Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. ‘public.user’) and/or table alias (e.g. ‘user u’). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression). You may also specify the table as an array with one element, using the array key as the table alias (e.g. [‘u’ => ‘user’]). To join a sub-query, use an array with one element, with the value set to a Query object representing the sub-query, and the corresponding key representing the alias.
$onstring|arrayThe join condition that should appear in the ON part. Please refer to where() on how to specify this parameter. Note that the array format of where() is designed to match columns to values instead of columns to columns, so the following would not work as expected: ['post.author_id' => 'user.id'], it would match the post.author_id column value against the string 'user.id'. It is recommended to use the string syntax here which is more suited for a join: ‘post.author_id = user.id’
$paramsarrayThe parameters (name => value) to be bound to the query.

Returns

$this: The query object itself

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

Appends a LEFT OUTER JOIN part to the query.

Parameters

ParameterTypeDescription
$tablestring|arrayThe table or sub-query to be joined. Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. ‘public.user’) and/or table alias (e.g. ‘user u’). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression). You may also specify the table as an array with one element, using the array key as the table alias (e.g. [‘u’ => ‘user’]). To join a sub-query, use an array with one element, with the value set to a Query object representing the sub-query, and the corresponding key representing the alias.
$onstring|arrayThe join condition that should appear in the ON part. Please refer to join() on how to specify this parameter.
$paramsarrayThe parameters (name => value) to be bound to the query

Returns

$this: The query object itself

public function max(string $q, yii\db\Connection|null $db = null): mixed

Returns the maximum of the specified column values.

Parameters

ParameterTypeDescription
$qstringThe column name or expression. Make sure you properly quote column names in the expression.
$dbConnection|nullThe database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.

Returns

mixed: The maximum of the specified column values.

public function min(string $q, yii\db\Connection|null $db = null): mixed

Returns the minimum of the specified column values.

Parameters

ParameterTypeDescription
$qstringThe column name or expression. Make sure you properly quote column names in the expression.
$dbConnection|nullThe database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.

Returns

mixed: The minimum of the specified column values.

public function noCache(): $this

Disables query cache for this Query.

Returns

$this: The Query object itself

Since

2.0.14

public function one(yii\db\Connection|null $db = null): array|bool

Executes the query and returns a single row of result.

Parameters

ParameterTypeDescription
$dbConnection|nullThe database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.

Returns

array|bool: The first row (in terms of an array) of the query result. False is returned if the query results in nothing.

public function orFilterHaving(array $condition): $this

Adds an additional HAVING condition to the existing one but ignores empty operands.

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 empty query operands. As a result, this method is best suited for building query conditions based on filter values entered by users.

Parameters

ParameterTypeDescription
$conditionarrayThe new HAVING condition. Please refer to having() on how to specify this parameter.

Returns

$this: The query object itself

Since

2.0.11

See also

public function orHaving(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this

Adds an additional HAVING condition to the existing one.

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

Parameters

ParameterTypeDescription
$conditionstring|array|ExpressionInterfaceThe new HAVING condition. Please refer to where() on how to specify this parameter.
$paramsarrayThe parameters (name => value) to be bound to the query.

Returns

$this: The query object itself

See also

public function orWhere(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this

Adds an additional WHERE condition to the existing one.

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

Parameters

ParameterTypeDescription
$conditionstring|array|ExpressionInterfaceThe new WHERE condition. Please refer to where() on how to specify this parameter.
$paramsarrayThe parameters (name => value) to be bound to the query.

Returns

$this: The query object itself

See also

public function params(array $params): $this

Sets the parameters to be bound to the query.

Parameters

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

Returns

$this: The query object itself

See also

public function populate(array $rows, yii\db\Connection|null $db = null): array

Converts the raw query results into the format as specified by this query.

This method is internally used to convert the data fetched from database into the format as required by this query.

Parameters

ParameterTypeDescription
$rowsarrayThe raw query result from database.
$dbConnection|nullThe database connection used to retrieve the rows.

Returns

array: The converted query result.

public function prepare(yii\db\QueryBuilder $builder): self

Prepares for building SQL.

This method is called by QueryBuilder 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 a SQL statement.

Parameters

ParameterTypeDescription
$builderQueryBuilder

Returns

self: A prepared query instance which will be used by QueryBuilder to build the SQL

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

Appends a RIGHT OUTER JOIN part to the query.

Parameters

ParameterTypeDescription
$tablestring|arrayThe table or sub-query to be joined. Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. ‘public.user’) and/or table alias (e.g. ‘user u’). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression). You may also specify the table as an array with one element, using the array key as the table alias (e.g. [‘u’ => ‘user’]). To join a sub-query, use an array with one element, with the value set to a Query object representing the sub-query, and the corresponding key representing the alias.
$onstring|arrayThe join condition that should appear in the ON part. Please refer to join() on how to specify this parameter.
$paramsarrayThe parameters (name => value) to be bound to the query

Returns

$this: The query object itself

public function scalar(yii\db\Connection|null $db = null): string|int|null|false

Returns the query result as a scalar value.

The value returned will be the first column in the first row of the query results.

Parameters

ParameterTypeDescription
$dbConnection|nullThe database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.

Returns

string|int|null|false: The value of the first column in the first row of the query result. False is returned if the query result is empty.

public function select(string|array|yii\db\ExpressionInterface $columns, string|null $option = null): $this

Sets the SELECT part of the query.

Parameters

ParameterTypeDescription
$columnsstring|array|ExpressionInterfaceThe columns to be selected. Columns can be specified in either a string (e.g. “id, name”) or an array (e.g. [‘id’, ‘name’]). Columns can be prefixed with table names (e.g. “user.id”) and/or contain column aliases (e.g. “user.id AS user_id”). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression). A DB expression may also be passed in form of an 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 does not need alias, do not use a string key). Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column as a Query instance representing the sub-query.
$optionstring|nullAdditional option that should be appended to the ‘SELECT’ keyword. For example, in MySQL, the option ‘SQL_CALC_FOUND_ROWS’ can be used.

Returns

$this: The query object itself

public function sum(string $q, yii\db\Connection|null $db = null): mixed

Returns the sum of the specified column values.

Parameters

ParameterTypeDescription
$qstringThe column name or expression. Make sure you properly quote column names in the expression.
$dbConnection|nullThe database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.

Returns

mixed: The sum of the specified column values.

public function union(string|yii\db\Query $sql, bool $all = false): $this

Appends a SQL statement using UNION operator.

orderBy(), limit(), and offset() configure the first SELECT statement. Use unionOrderBy(), unionLimit(), and unionOffset() to configure the complete UNION result.

Parameters

ParameterTypeDescription
$sqlstring|QueryThe SQL statement to be appended using UNION
$allboolTRUE if using UNION ALL and FALSE if using UNION

Returns

$this: The query object itself

public function unionLimit(int|yii\db\ExpressionInterface|null $limit): static

Sets the LIMIT part of the complete UNION result.

Parameters

ParameterTypeDescription
$limitint|ExpressionInterface|nullThe limit. Use null or a negative value to disable it.

Returns

static: The query object itself.

Since

22.0

public function unionOffset(int|yii\db\ExpressionInterface|null $offset): static

Sets the OFFSET part of the complete UNION result.

Parameters

ParameterTypeDescription
$offsetint|ExpressionInterface|nullThe offset. Use null or a negative value to disable it.

Returns

static: The query object itself.

Since

22.0

public function unionOrderBy(array<int|string, int|yii\db\ExpressionInterface>|string|yii\db\ExpressionInterface|null $columns): static

Sets the ORDER BY part of the complete UNION result.

Parameters

ParameterTypeDescription
$columnsarray<int|string, int|ExpressionInterface>|string|ExpressionInterface|nullThe columns (and the directions) to be ordered by.

Returns

static: The query object itself.

Since

22.0

See also

public function where(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this

Sets the WHERE part of the query.

The method requires a $condition parameter, and optionally a $params parameter specifying the values to be bound to the query.

The $condition parameter should be either a string (e.g. 'id=1') or an array.

Parameters

ParameterTypeDescription
$conditionstring|array|ExpressionInterfaceThe conditions that should be put in the WHERE part.
$paramsarrayThe parameters (name => value) to be bound to the query.

Returns

$this: The query object itself

See also

public function withQuery(string|yii\db\Query $query, string $alias, bool $recursive = false): $this

Prepends a SQL statement using WITH syntax.

Parameters

ParameterTypeDescription
$querystring|QueryThe SQL statement to be prepended using WITH
$aliasstringQuery alias in WITH construction
$recursiveboolTRUE if using WITH RECURSIVE and FALSE if using WITH

Returns

$this: The query object itself

Since

2.0.35

protected function cleanUpTableNames(array $tableNames): string[]

Clean up table names and aliases Both aliases and names are enclosed into {{ and }}.

Parameters

ParameterTypeDescription
$tableNamesarrayNon-empty array

Returns

string[]: Table names indexed by aliases

Since

2.0.14

protected function normalizeSelect(string|array|yii\db\ExpressionInterface $columns): array

Normalizes the SELECT columns passed to select() or addSelect().

Parameters

ParameterTypeDescription
$columnsstring|array|ExpressionInterface

Returns

array

Since

2.0.21

protected function queryScalar(string|yii\db\ExpressionInterface $selectExpression, yii\db\Connection|null $db): bool|string|null

Queries a scalar value by setting select() first.

Restores the value of select to make this query reusable.

Parameters

ParameterTypeDescription
$selectExpressionstring|ExpressionInterface
$dbConnection|nullThe database connection used to execute the query.

Returns

bool|string|null

Throws

protected function setCommandCache(yii\db\Command $command): yii\db\Command

Sets $command cache, if this query has enabled caching.

Parameters

ParameterTypeDescription
$commandCommand

Returns

Command

Since

2.0.14