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.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$distinct | bool | Whether to select distinct rows of data only. Default: false. | Query |
$emulateExecution | bool | Whether to emulate the actual query execution, returning empty or false results. Default: false. Available since 2.0.11. | QueryTrait |
$from | array| | The table(s) to be selected from. Default: null. | Query |
$groupBy | array| | How to group the query results. Default: null. | Query |
$having | string|ExpressionInterface| | The condition to be applied in the GROUP BY clause. Default: null. | Query |
$indexBy | string| | The name of the column by which the query results should be indexed by. Default: null. | QueryTrait |
$join | array| | How to join with other tables. Default: null. | Query |
$limit | int|ExpressionInterface| | Maximum number of records to be returned. Default: null. | QueryTrait |
$offset | int|ExpressionInterface| | Zero-based offset from where the records are to be returned. Default: null. | QueryTrait |
$orderBy | array| | How to sort the query results. Default: null. | QueryTrait |
$params | array| | List of query parameter values indexed by parameter placeholders. Default: []. | Query |
$queryCacheDependency | yii\| | The dependency to be associated with the cached query result for this query Default: null. Available since 2.0.14. | Query |
$queryCacheDuration | int| | The default number of seconds that query results can remain valid in cache. Default: null. Available since 2.0.14. | Query |
$select | array| | The columns being selected. Default: null. | Query |
$selectOption | string| | Additional option that should be appended to the ‘SELECT’ keyword. Default: null. | Query |
$tablesUsedInFrom read-only | string[] | Table names indexed by aliases. | Query |
$union | array| | This is used to construct the UNION clause(s) in a SQL statement. Default: null. | Query |
$unionLimit | int|ExpressionInterface| | Number of records to return from the complete UNION result. Default: null. Available since 22.0. | Query |
$unionOffset | int|ExpressionInterface| | Zero-based offset for the complete UNION result. Default: null. Available since 22.0. | Query |
$unionOrderBy | array<int|ExpressionInterface>| | How to sort the complete UNION result. Default: null. Available since 22.0. | Query |
$where | string|ExpressionInterface| | Query condition. Default: null. | QueryTrait |
$withQueries | array| | This is used to construct the WITH section in a SQL query. Default: null. Available since 2.0.35. | Query |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__toString() | Returns the SQL representation of Query | Query |
__unset() | Sets a component property to be null. | yii\ |
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\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
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\ |
cache() | Enables query cache for this Query. | Query |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
column() | Executes the query and returns the first column of the result. | Query |
count() | Returns the number of records. | Query |
create() static | Creates 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\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
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\ |
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\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
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\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
having() | Sets the HAVING part of the query. | Query |
indexBy() | Sets the indexBy() property. | QueryTrait |
init() | Initializes the object. | yii\ |
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\ |
offset() | Sets the OFFSET part of the query. | QueryTrait |
on() | Attaches an event handler to an event. | yii\ |
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\ |
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() protected | Clean up table names and aliases Both aliases and names are enclosed into {{ and }}. | Query |
filterCondition() protected | Removes empty operands from the given query condition. | QueryTrait |
isEmpty() protected | Returns a value indicating whether the give value is “empty”. | QueryTrait |
normalizeOrderBy() protected | Normalizes format of ORDER BY data. | QueryTrait |
normalizeSelect() protected | Normalizes the SELECT columns passed to select() or addSelect(). | Query |
queryScalar() protected | Queries a scalar value by setting select() first. | Query |
setCommandCache() protected | Sets $command cache, if this query has enabled caching. | Query |
Property details
Section titled “Property details”$distinct
Section titled “$distinct ”public bool $distinct = falseWhether to select distinct rows of data only.
If this is set true, the SELECT clause would be changed to SELECT DISTINCT.
$from
Section titled “$from ”public array|string|null $from = nullThe table(s) to be selected from.
For example, ['user', 'post'].
This is used to construct the FROM clause in a SQL statement.
$groupBy
Section titled “$groupBy ”public array|null $groupBy = nullHow to group the query results.
For example, ['company', 'department'].
This is used to construct the GROUP BY clause in a SQL statement.
$having
Section titled “$having ”public string|array|yii\db\ExpressionInterface|null $having = nullThe 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.
$join
Section titled “$join ”public array|null $join = nullHow 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'],]$params
Section titled “$params ”public array|null $params = []List of query parameter values indexed by parameter placeholders.
For example, [':name' => 'Dan', ':age' => 31].
$queryCacheDuration
Section titled “$queryCacheDuration ”public int|bool|null $queryCacheDuration = nullThe 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
$select
Section titled “$select ”public array|null $select = nullThe 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.
$selectOption
Section titled “$selectOption ”public string|null $selectOption = nullAdditional option that should be appended to the ‘SELECT’ keyword.
For example, in MySQL, the option ‘SQL_CALC_FOUND_ROWS’ can be used.
$union
Section titled “$union ”public array|null $union = nullThis 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 aQueryobject representing a queryall: boolean, whether it should beUNION ALLorUNION
$withQueries
Section titled “$withQueries ”public array|null $withQueries = nullThis 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 aQueryobject representing a queryalias: string, alias of query for further usagerecursive: boolean, whether it should beWITH RECURSIVEorWITH
Since
2.0.35
Method details
Section titled “Method details”__toString()
Section titled “__toString() ”public function __toString(): stringReturns the SQL representation of Query
Returns
string
addGroupBy()
Section titled “addGroupBy() ”public function addGroupBy(string|array|yii\db\ExpressionInterface $columns): $thisAdds additional group-by columns to the existing ones.
Parameters
| Parameter | Type | Description |
|---|---|---|
$columns | string|ExpressionInterface | Additional 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
addParams()
Section titled “addParams() ”public function addParams(array $params): $thisAdds additional parameters to be bound to the query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$params | array | List of query parameter values indexed by parameter placeholders. For example, [':name' => 'Dan',. |
Returns
$this: The query object itself
See also
addSelect()
Section titled “addSelect() ”public function addSelect(string|array|yii\db\ExpressionInterface $columns): $thisAdd 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
| Parameter | Type | Description |
|---|---|---|
$columns | string|ExpressionInterface | The 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
addUnionOrderBy()
Section titled “addUnionOrderBy() ”public function addUnionOrderBy(array<int|string, int|yii\db\ExpressionInterface>|string|yii\db\ExpressionInterface|null $columns): staticAdds ORDER BY columns to the complete UNION result.
Parameters
| Parameter | Type | Description |
|---|---|---|
$columns | array<int|ExpressionInterface>|ExpressionInterface| | The columns (and the directions) to be ordered by. |
Returns
static: The query object itself.
Since
22.0
See also
all()
Section titled “all() ”public function all(yii\db\Connection|null $db = null): arrayExecutes the query and returns all results as an array.
Parameters
| Parameter | Type | Description |
|---|---|---|
$db | Connection| | The 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.
andFilterCompare()
Section titled “andFilterCompare() ”public function andFilterCompare(string $name, string $value, string $defaultOperator = '='): $thisAdds 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
$defaultOperatorwill be used.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The column name. |
$value | string | 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. |
Returns
$this: The query object itself
Since
2.0.8
andFilterHaving()
Section titled “andFilterHaving() ”public function andFilterHaving(array $condition): $thisAdds 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
| Parameter | Type | Description |
|---|---|---|
$condition | array | The 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
andHaving()
Section titled “andHaving() ”public function andHaving(string|array|yii\db\ExpressionInterface $condition, array $params = []): $thisAdds an additional HAVING condition to the existing one.
The new condition and the existing one will be joined using the AND operator.
Parameters
| Parameter | Type | Description |
|---|---|---|
$condition | string|ExpressionInterface | 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. |
Returns
$this: The query object itself
See also
andWhere()
Section titled “andWhere() ”public function andWhere(string|array|yii\db\ExpressionInterface $condition, array $params = []): $thisAdds an additional WHERE condition to the existing one.
The new condition and the existing one will be joined using the AND operator.
Parameters
| Parameter | Type | Description |
|---|---|---|
$condition | string|ExpressionInterface | 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. |
Returns
$this: The query object itself
See also
average()
Section titled “average() ”public function average(string $q, yii\db\Connection|null $db = null): mixedReturns the average of the specified column values.
Parameters
| Parameter | Type | Description |
|---|---|---|
$q | string | The column name or expression. Make sure you properly quote column names in the expression. |
$db | Connection| | The 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.
batch()
Section titled “batch() ”public function batch(int $batchSize = 100, yii\db\Connection|null $db = null): yii\db\BatchQueryResultStarts 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
| Parameter | Type | Description |
|---|---|---|
$batchSize | int | The number of records to be fetched in each batch. |
$db | Connection| | The 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.
cache()
Section titled “cache() ”public function cache(int|true $duration = true, yii\caching\Dependency|null $dependency = null): $thisEnables query cache for this Query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$duration | int| | The 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. |
$dependency | yii\| | The cache dependency associated with the cached result. |
Returns
$this: The Query object itself
Since
2.0.14
column()
Section titled “column() ”public function column(yii\db\Connection|null $db = null): arrayExecutes the query and returns the first column of the result.
Parameters
| Parameter | Type | Description |
|---|---|---|
$db | Connection| | The 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.
count()
Section titled “count() ”public function count(string $q = '*', yii\db\Connection|null $db = null): int|string|nullReturns the number of records.
Parameters
| Parameter | Type | Description |
|---|---|---|
$q | string | The COUNT expression. Defaults to ’*’. Make sure you properly quote column names in the expression. |
$db | Connection| | The 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.
create()
Section titled “create() ”public static function create(yii\db\Query $from): yii\db\QueryCreates 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.
createCommand()
Section titled “createCommand() ”public function createCommand(yii\db\Connection|null $db = null): yii\db\CommandCreates a DB command that can be used to execute this query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$db | Connection| | The 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.
distinct()
Section titled “distinct() ”public function distinct(bool $value = true): $thisSets the value indicating whether to SELECT DISTINCT or not.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | bool | Whether to SELECT DISTINCT or not. |
Returns
$this: The query object itself
each()
Section titled “each() ”public function each(int $batchSize = 100, yii\db\Connection|null $db = null): yii\db\BatchQueryResultStarts 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
| Parameter | Type | Description |
|---|---|---|
$batchSize | int | The number of records to be fetched in each batch. |
$db | Connection| | The 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.
exists()
Section titled “exists() ”public function exists(yii\db\Connection|null $db = null): boolReturns a value indicating whether the query result contains any row of data.
Parameters
| Parameter | Type | Description |
|---|---|---|
$db | Connection| | The 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.
filterHaving()
Section titled “filterHaving() ”public function filterHaving(array $condition): $thisSets 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
| Parameter | Type | Description |
|---|---|---|
$condition | array | The 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
from()
Section titled “from() ”public function from(string|array|yii\db\ExpressionInterface $tables): $thisSets the FROM part of the query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$tables | string|ExpressionInterface | The table(s) to be selected from. This can be either a string (e.g. 'user') or an array (e.g. ['user',) 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
getTablesUsedInFrom()
Section titled “getTablesUsedInFrom() ”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
groupBy()
Section titled “groupBy() ”public function groupBy(string|array|yii\db\ExpressionInterface|null $columns): $thisSets the GROUP BY part of the query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$columns | string|ExpressionInterface| | The 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
having()
Section titled “having() ”public function having(string|array|yii\db\ExpressionInterface $condition, array $params = []): $thisSets the HAVING part of the query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$condition | string|ExpressionInterface | The conditions to be put after HAVING. Please refer to where() on how to specify this parameter. |
$params | array | The parameters (name => value) to be bound to the query. |
Returns
$this: The query object itself
See also
innerJoin()
Section titled “innerJoin() ”public function innerJoin(string|array $table, string|array $on = '', array $params = []): $thisAppends an INNER JOIN part to the query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$table | string| | The 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. |
$on | 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. |
Returns
$this: The query object itself
join()
Section titled “join() ”public function join(string $type, string|array $table, string|array $on = '', array $params = []): $thisAppends a JOIN part to the query.
The first parameter specifies what type of join it is.
Parameters
| Parameter | Type | Description |
|---|---|---|
$type | string | The type of join, such as INNER JOIN, LEFT JOIN. |
$table | string| | The 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. |
$on | string| | The 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’ |
$params | array | The parameters (name => value) to be bound to the query. |
Returns
$this: The query object itself
leftJoin()
Section titled “leftJoin() ”public function leftJoin(string|array $table, string|array $on = '', array $params = []): $thisAppends a LEFT OUTER JOIN part to the query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$table | string| | The 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. |
$on | 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 |
Returns
$this: The query object itself
max()
Section titled “max() ”public function max(string $q, yii\db\Connection|null $db = null): mixedReturns the maximum of the specified column values.
Parameters
| Parameter | Type | Description |
|---|---|---|
$q | string | The column name or expression. Make sure you properly quote column names in the expression. |
$db | Connection| | The 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.
min()
Section titled “min() ”public function min(string $q, yii\db\Connection|null $db = null): mixedReturns the minimum of the specified column values.
Parameters
| Parameter | Type | Description |
|---|---|---|
$q | string | The column name or expression. Make sure you properly quote column names in the expression. |
$db | Connection| | The 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.
noCache()
Section titled “noCache() ”public function noCache(): $thisDisables query cache for this Query.
Returns
$this: The Query object itself
Since
2.0.14
one()
Section titled “one() ”public function one(yii\db\Connection|null $db = null): array|boolExecutes the query and returns a single row of result.
Parameters
| Parameter | Type | Description |
|---|---|---|
$db | Connection| | The 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.
orFilterHaving()
Section titled “orFilterHaving() ”public function orFilterHaving(array $condition): $thisAdds 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
| Parameter | Type | Description |
|---|---|---|
$condition | array | The 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
orHaving()
Section titled “orHaving() ”public function orHaving(string|array|yii\db\ExpressionInterface $condition, array $params = []): $thisAdds an additional HAVING condition to the existing one.
The new condition and the existing one will be joined using the OR operator.
Parameters
| Parameter | Type | Description |
|---|---|---|
$condition | string|ExpressionInterface | 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. |
Returns
$this: The query object itself
See also
orWhere()
Section titled “orWhere() ”public function orWhere(string|array|yii\db\ExpressionInterface $condition, array $params = []): $thisAdds an additional WHERE condition to the existing one.
The new condition and the existing one will be joined using the OR operator.
Parameters
| Parameter | Type | Description |
|---|---|---|
$condition | string|ExpressionInterface | 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. |
Returns
$this: The query object itself
See also
params()
Section titled “params() ”public function params(array $params): $thisSets the parameters to be bound to the query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$params | array | List of query parameter values indexed by parameter placeholders. For example, [':name' => 'Dan',. |
Returns
$this: The query object itself
See also
populate()
Section titled “populate() ”public function populate(array $rows, yii\db\Connection|null $db = null): arrayConverts 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
| Parameter | Type | Description |
|---|---|---|
$rows | array | The raw query result from database. |
$db | Connection| | The database connection used to retrieve the rows. |
Returns
array: The converted query result.
prepare()
Section titled “prepare() ”public function prepare(yii\db\QueryBuilder $builder): selfPrepares 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
| Parameter | Type | Description |
|---|---|---|
$builder | QueryBuilder |
Returns
self: A prepared query instance which will be used by QueryBuilder to build the SQL
rightJoin()
Section titled “rightJoin() ”public function rightJoin(string|array $table, string|array $on = '', array $params = []): $thisAppends a RIGHT OUTER JOIN part to the query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$table | string| | The 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. |
$on | 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 |
Returns
$this: The query object itself
scalar()
Section titled “scalar() ”public function scalar(yii\db\Connection|null $db = null): string|int|null|falseReturns the query result as a scalar value.
The value returned will be the first column in the first row of the query results.
Parameters
| Parameter | Type | Description |
|---|---|---|
$db | Connection| | The 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.
select()
Section titled “select() ”public function select(string|array|yii\db\ExpressionInterface $columns, string|null $option = null): $thisSets the SELECT part of the query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$columns | string|ExpressionInterface | The 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,, 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. |
$option | string| | Additional 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
sum()
Section titled “sum() ”public function sum(string $q, yii\db\Connection|null $db = null): mixedReturns the sum of the specified column values.
Parameters
| Parameter | Type | Description |
|---|---|---|
$q | string | The column name or expression. Make sure you properly quote column names in the expression. |
$db | Connection| | The 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.
union()
Section titled “union() ”public function union(string|yii\db\Query $sql, bool $all = false): $thisAppends 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
| Parameter | Type | Description |
|---|---|---|
$sql | string|Query | The SQL statement to be appended using UNION |
$all | bool | TRUE if using UNION ALL and FALSE if using UNION |
Returns
$this: The query object itself
unionLimit()
Section titled “unionLimit() ”public function unionLimit(int|yii\db\ExpressionInterface|null $limit): staticSets the LIMIT part of the complete UNION result.
Parameters
| Parameter | Type | Description |
|---|---|---|
$limit | int|ExpressionInterface| | The limit. Use null or a negative value to disable it. |
Returns
static: The query object itself.
Since
22.0
unionOffset()
Section titled “unionOffset() ”public function unionOffset(int|yii\db\ExpressionInterface|null $offset): staticSets the OFFSET part of the complete UNION result.
Parameters
| Parameter | Type | Description |
|---|---|---|
$offset | int|ExpressionInterface| | The offset. Use null or a negative value to disable it. |
Returns
static: The query object itself.
Since
22.0
unionOrderBy()
Section titled “unionOrderBy() ”public function unionOrderBy(array<int|string, int|yii\db\ExpressionInterface>|string|yii\db\ExpressionInterface|null $columns): staticSets the ORDER BY part of the complete UNION result.
Parameters
| Parameter | Type | Description |
|---|---|---|
$columns | array<int|ExpressionInterface>|ExpressionInterface| | The columns (and the directions) to be ordered by. |
Returns
static: The query object itself.
Since
22.0
See also
where()
Section titled “where() ”public function where(string|array|yii\db\ExpressionInterface $condition, array $params = []): $thisSets 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
| Parameter | Type | Description |
|---|---|---|
$condition | string|ExpressionInterface | The conditions that should be put in the WHERE part. |
$params | array | The parameters (name => value) to be bound to the query. |
Returns
$this: The query object itself
See also
withQuery()
Section titled “withQuery() ”public function withQuery(string|yii\db\Query $query, string $alias, bool $recursive = false): $thisPrepends a SQL statement using WITH syntax.
Parameters
| Parameter | Type | Description |
|---|---|---|
$query | string|Query | The SQL statement to be prepended using WITH |
$alias | string | Query alias in WITH construction |
$recursive | bool | TRUE if using WITH RECURSIVE and FALSE if using WITH |
Returns
$this: The query object itself
Since
2.0.35
cleanUpTableNames()
Section titled “cleanUpTableNames() ”protected function cleanUpTableNames(array $tableNames): string[]Clean up table names and aliases Both aliases and names are enclosed into {{ and }}.
Parameters
| Parameter | Type | Description |
|---|---|---|
$tableNames | array | Non-empty array |
Returns
string[]: Table names indexed by aliases
Since
2.0.14
normalizeSelect()
Section titled “normalizeSelect() ”protected function normalizeSelect(string|array|yii\db\ExpressionInterface $columns): arrayNormalizes the SELECT columns passed to select() or addSelect().
Parameters
| Parameter | Type | Description |
|---|---|---|
$columns | string|ExpressionInterface |
Returns
array
Since
2.0.21
queryScalar()
Section titled “queryScalar() ”protected function queryScalar(string|yii\db\ExpressionInterface $selectExpression, yii\db\Connection|null $db): bool|string|nullQueries a scalar value by setting select() first.
Restores the value of select to make this query reusable.
Parameters
| Parameter | Type | Description |
|---|---|---|
$selectExpression | string|ExpressionInterface | |
$db | Connection| | The database connection used to execute the query. |
Returns
bool|string|null
Throws
Throwable: if can’t create command
setCommandCache()
Section titled “setCommandCache() ”protected function setCommandCache(yii\db\Command $command): yii\db\CommandSets $command cache, if this query has enabled caching.