ActiveQuery
API reference › yii › db › ActiveQuery
ActiveQuery represents a DB query associated with an Active Record class.
An ActiveQuery can be a normal query or be used in a relational context.
ActiveQuery instances are usually created by ActiveRecord::find() and ActiveRecord::findBySql().
Relational queries are created by ActiveRecord::hasOne() and ActiveRecord::hasMany().
Normal Query
Section titled “Normal Query”ActiveQuery mainly provides the following methods to retrieve the query results:
one(): returns a single record populated with the first row of data.all(): returns all records based on the query results.count(): returns the number of records.sum(): returns the sum over the specified column.average(): returns the average over the specified column.min(): returns the min over the specified column.max(): returns the max over the specified column.scalar(): returns the value of the first column in the first row of the query result.column(): returns the value of the first column in the query result.exists(): returns a value indicating whether the query result has data or not.
Because ActiveQuery extends from Query, one can use query methods, such as where(),
orderBy() to customize the query options.
ActiveQuery also provides the following additional query options:
with(): list of relations that this query should be performed with.joinWith(): reuse a relation query definition to add a join to a query.indexBy(): the name of the column by which the query result should be indexed.asArray(): whether to return each record as an array.
These options can be configured using methods of the same name. For example:
$customers = Customer::find()->with('orders')->asArray()->all();Relational query
Section titled “Relational query”In relational context ActiveQuery represents a relation between two Active Record classes.
Relational ActiveQuery instances are usually created by calling ActiveRecord::hasOne() and
ActiveRecord::hasMany(). An Active Record class declares a relation by defining
a getter method which calls one of the above methods and returns the created ActiveQuery object.
A relation is specified by $link which represents the association between columns
of different tables; and the multiplicity of the relation is indicated by $multiple.
If a relation involves a junction table, it may be specified by via() or viaTable() method.
These methods may only be called in a relational context. Same is true for inverseOf(), which
marks a relation as inverse of another relation and onCondition() which adds a condition that
is to be added to relational query join condition.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$asArray | bool | Whether to return each record as an array. Default: null. | ActiveQueryTrait |
$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 |
$inverseOf | string | The name of the relation that is the inverse of this relation. Default: null. | ActiveRelationTrait |
$join | array| | How to join with other tables. Default: null. | Query |
$joinWith | array| | A list of relations that this query should be joined with Default: null. | ActiveQuery |
$limit | int|ExpressionInterface| | Maximum number of records to be returned. Default: null. | QueryTrait |
$link | array | The columns of the primary and foreign tables that establish a relation. Default: null. | ActiveRelationTrait |
$modelClass | class-string<ActiveRecordInterface> | The name of the ActiveRecord class. Default: null. | ActiveQueryTrait |
$multiple | bool | Whether this query represents a relation to more than one record. Default: null. | ActiveRelationTrait |
$offset | int|ExpressionInterface| | Zero-based offset from where the records are to be returned. Default: null. | QueryTrait |
$on | string| | The join condition to be used when this query is used in a relational context. Default: null. | ActiveQuery |
$orderBy | array| | How to sort the query results. Default: null. | QueryTrait |
$params | array| | List of query parameter values indexed by parameter placeholders. Default: []. | Query |
$primaryModel | ActiveRecord | The primary model of a relational query. Default: null. | ActiveRelationTrait |
$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 |
$sql | string| | The SQL statement to be executed for retrieving AR records. Default: null. | ActiveQuery |
$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 |
$via | array| | The query associated with the junction table. Default: null. | ActiveRelationTrait |
$where | string|ExpressionInterface| | Query condition. Default: null. | QueryTrait |
$with | array| | A list of relations that this query should be performed with Default: null. | ActiveQueryTrait |
$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. | ActiveQuery |
__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 |
alias() | Define an alias for the table defined in $modelClass. | ActiveQuery |
all() | Executes query and returns all results as an array. | ActiveQuery |
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 |
andOnCondition() | Adds an additional ON condition to the existing one. | ActiveQuery |
andWhere() | Adds an additional WHERE condition to the existing one. | Query |
asArray() | Sets the asArray() property. | ActiveQuery |
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() | The batch query result. | ActiveQuery |
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. | ActiveQuery |
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() | The batch query result. | ActiveQuery |
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 |
findFor() | Finds the related records for the specified primary record. | ActiveRelationTrait |
findWith() | Finds records corresponding to one or multiple relations and populates them into the primary models. | ActiveQueryTrait |
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. | ActiveQuery |
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. | ActiveQuery |
innerJoin() | Appends an INNER JOIN part to the query. | Query |
innerJoinWith() | Inner joins with the specified relations. | ActiveQuery |
inverseOf() | Sets the name of the relation that is the inverse of this relation. | ActiveRelationTrait |
join() | Appends a JOIN part to the query. | Query |
joinWith() | Joins with the specified relations. | ActiveQuery |
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\ |
onCondition() | Sets the ON condition for a relational query. | ActiveQuery |
one() | Executes query and returns a single row of result. | ActiveQuery |
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 |
orOnCondition() | Adds an additional ON condition to the existing one. | ActiveQuery |
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. | ActiveQuery |
populateRelation() | Finds the related records and populates them into the primary models. | ActiveRelationTrait |
prepare() | Prepares for building SQL. | ActiveQuery |
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 |
via() | Specifies the relation associated with the junction table. | ActiveRelationTrait |
viaTable() | Specifies the junction table for a relational query. | ActiveQuery |
where() | Sets the WHERE part of the query. | Query |
with() | Specifies the relations with which this query should be performed. | ActiveQueryTrait |
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 |
createModels() protected | Converts found rows into model instances. | ActiveQueryTrait |
filterCondition() protected | Removes empty operands from the given query condition. | QueryTrait |
getPrimaryTableName() protected | ActiveQuery | |
getTableNameAndAlias() protected | Returns the table name and the table alias for $modelClass. | ActiveQuery |
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. | ActiveQuery |
setCommandCache() protected | Sets $command cache, if this query has enabled caching. | Query |
Events
Section titled “Events”| Event | Type | Description | Defined by |
|---|---|---|---|
EVENT_INIT | yii\ | An event that is triggered when the query is initialized via init(). Event name: 'init'. | ActiveQuery |
Property details
Section titled “Property details”public string|array|null $on = nullThe join condition to be used when this query is used in a relational context.
The condition will be used in the ON part when ActiveQuery::joinWith() is called.
Otherwise, the condition will be used in the WHERE part of a query.
Please refer to Query::where() on how to specify this parameter.
public string|null $sql = nullThe SQL statement to be executed for retrieving AR records.
This is set by ActiveRecord::findBySql().
Method details
Section titled “Method details”__construct()
Section titled “__construct() ”public function __construct(class-string<yii\db\ActiveRecordInterface> $modelClass, array $config = [])Constructor.
Parameters
| Parameter | Type | Description |
|---|---|---|
$modelClass | class-string<ActiveRecordInterface> | The model class associated with this query |
$config | array | Configurations to be applied to the newly created query object |
alias()
Section titled “alias() ”public function alias(string $alias): $thisDefine an alias for the table defined in $modelClass.
This method will adjust from() so that an already defined alias will be overwritten.
If none was defined, from() will be populated with the given alias.
Parameters
| Parameter | Type | Description |
|---|---|---|
$alias | string | The table alias. |
Returns
$this: The query object itself
Since
2.0.7
all()
Section titled “all() ”public function all(yii\db\Connection|null $db = null): yii\db\T[]Executes query and returns all results as an array.
Parameters
| Parameter | Type | Description |
|---|---|---|
$db | Connection| | The DB connection used to create the DB command. If null, the DB connection returned by $modelClass will be used. |
Returns
yii\db\T[]: The query results. If the query results in nothing, an empty array will be returned.
andOnCondition()
Section titled “andOnCondition() ”public function andOnCondition(string|array $condition, array $params = []): $thisAdds an additional ON 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| | The new ON 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
asArray()
Section titled “asArray() ”public function asArray(mixed $value): ($value is true ? (yii\db\T is array ? static<yii\db\T> : static<array<string, mixed>>) : static<yii\db\T>)Sets the asArray() property.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed |
Returns
($value is true ? (yii\db\T is array ? static<yii\db\T> : static<array<string, mixed>>) : static<yii\db\T>)
batch()
Section titled “batch() ”public function batch(mixed $batchSize, mixed $db): yii\db\BatchQueryResult<int, yii\db\T[]>The batch query result.
It implements the Iterator interface
and can be traversed to retrieve the data in batches.
Parameters
| Parameter | Type | Description |
|---|---|---|
$batchSize | mixed | |
$db | mixed |
Returns
BatchQueryResult<int, yii\db\T[]>
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 DB connection used to create the DB command. If null, the DB connection returned by $modelClass will be used. |
Returns
Command: The created DB command instance.
each()
Section titled “each() ”public function each(mixed $batchSize, mixed $db): yii\db\BatchQueryResult<array-key, yii\db\T>The batch query result.
It implements the Iterator interface
and can be traversed to retrieve the data in batches.
Parameters
| Parameter | Type | Description |
|---|---|---|
$batchSize | mixed | |
$db | mixed |
Returns
BatchQueryResult<array-key, yii\db\T>
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
init()
Section titled “init() ”public function init(): mixedInitializes the object.
This method is called at the end of the constructor. The default implementation will trigger
an EVENT_INIT event. If you override this method, make sure you call the parent implementation at the end
to ensure triggering of the event.
Returns
mixed
innerJoinWith()
Section titled “innerJoinWith() ”public function innerJoinWith(string|array $with, bool|array $eagerLoading = true): $thisInner joins with the specified relations.
This is a shortcut method to joinWith() with the join type set as “INNER JOIN”.
Please refer to joinWith() for detailed usage of this method.
Parameters
| Parameter | Type | Description |
|---|---|---|
$with | string| | The relations to be joined with. |
$eagerLoading | bool| | Whether to eager load the relations. Note, that this does not mean, that the relations are populated from the query result. An extra query will still be performed to bring in the related data. |
Returns
$this: The query object itself
See also
joinWith()
Section titled “joinWith() ”public function joinWith(string|array $with, bool|array $eagerLoading = true, string|array $joinType = 'LEFT JOIN'): $thisJoins with the specified relations.
This method allows you to reuse existing relation definitions to perform JOIN queries. Based on the definition of the specified relation(s), the method will append one or multiple JOIN statements to the current query.
If the $eagerLoading parameter is true, the method will also perform eager loading for the specified relations,
which is equivalent to calling with() using the specified relations.
Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
This method differs from with() in that it will build up and execute a JOIN SQL statement
for the primary table. And when $eagerLoading is true, it will call with() in addition with the specified relations.
Parameters
| Parameter | Type | Description |
|---|---|---|
$with | string| | The relations to be joined. This can either be a string, representing a relation name or an array with the following semantics: - Each array element represents a single relation. - You may specify the relation name as the array key and provide an anonymous functions that can be used to modify the relation queries on-the-fly as the array value. - If a relation query does not need modification, you may use the relation name as the array value. The relation name may optionally contain an alias for the relation table (e.g. books b). Sub-relations can also be specified, see with() for the syntax. In the following you find some examples: // find all orders that contain books, and eager loading “books” Order::find()->joinWith(‘books’, true, ‘INNER JOIN’)->all(); // find all orders, eager loading “books”, and sort the orders and books by the book names. Order::find()->joinWith([ ‘books’ => function (\yii\db\ActiveQuery $query) { $query->orderBy(‘item.name’); } ])->all(); // find all orders that contain books of the category ‘Science fiction’, using the alias “b” for the books table Order::find()->joinWith([‘books b’], true, ‘INNER JOIN’)->where([‘b.category’ => ‘Science fiction’])->all(); The alias syntax is available since version 2.0.7. |
$eagerLoading | bool| | Whether to eager load the relations specified in $with. When this is a boolean, it applies to all relations specified in $with. Use an array to explicitly list which relations in $with need to be eagerly loaded. Note, that this does not mean, that the relations are populated from the query result. An extra query will still be performed to bring in the related data. Defaults to true. |
$joinType | string| | The join type of the relations specified in $with. When this is a string, it applies to all relations specified in $with. Use an array in the format of relationName => joinType to specify different join types for different relations. |
Returns
$this: The query object itself
onCondition()
Section titled “onCondition() ”public function onCondition(string|array $condition, array $params = []): $thisSets the ON condition for a relational query.
The condition will be used in the ON part when ActiveQuery::joinWith() is called.
Otherwise, the condition will be used in the WHERE part of a query.
Use this method to specify additional conditions when declaring a relation in the ActiveRecord class:
public function getActiveUsers(){ return $this->hasMany(User::class, ['id' => 'user_id']) ->onCondition(['active' => true]);}Note that this condition is applied in case of a join as well as when fetching the related records. Thus only fields of the related table can be used in the condition. Trying to access fields of the primary record will cause an error in a non-join-query.
Parameters
| Parameter | Type | Description |
|---|---|---|
$condition | string| | The ON condition. Please refer to Query::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
one()
Section titled “one() ”public function one(yii\db\Connection|null $db = null): yii\db\T|nullExecutes query and returns a single row of result.
Parameters
| Parameter | Type | Description |
|---|---|---|
$db | Connection| | The DB connection used to create the DB command. If null, the DB connection returned by $modelClass will be used. |
Returns
yii\db\T|null: A single row of query result. Depending on the setting of asArray(), the query result may be either an array or an ActiveRecord object. null will be returned if the query results in nothing.
orOnCondition()
Section titled “orOnCondition() ”public function orOnCondition(string|array $condition, array $params = []): $thisAdds an additional ON 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| | The new ON 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
populate()
Section titled “populate() ”public function populate(mixed $rows, mixed $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 | mixed | The raw query result from database. |
$db | mixed | The database connection used to retrieve the rows. |
Returns
array: The converted query result.
prepare()
Section titled “prepare() ”public function prepare(mixed $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 | mixed |
Returns
self: A prepared query instance which will be used by QueryBuilder to build the SQL
viaTable()
Section titled “viaTable() ”public function viaTable(string $tableName, array $link, callable|null $callable = null): $thisSpecifies the junction table for a relational query.
Use this method to specify a junction table when declaring a relation in the ActiveRecord class:
public function getItems(){ return $this->hasMany(Item::class, ['id' => 'item_id']) ->viaTable('order_item', ['order_id' => 'id']);}Parameters
| Parameter | Type | Description |
|---|---|---|
$tableName | string | The name of the junction table. |
$link | array | The link between the junction table and the table associated with $primaryModel. The keys of the array represent the columns in the junction table, and the values represent the columns in the $primaryModel table. |
$callable | callable| | A PHP callback for customizing the relation associated with the junction table. Its signature should be function($query), where $query is the query to be customized. |
Returns
$this: The query object itself
Throws
yii\base\InvalidConfigException: when query is not initialized properly
See also
getPrimaryTableName()
Section titled “getPrimaryTableName() ”protected function getPrimaryTableName(): stringReturns
string: Primary table name
Since
2.0.12
getTableNameAndAlias()
Section titled “getTableNameAndAlias() ”protected function getTableNameAndAlias(): arrayReturns the table name and the table alias for $modelClass.
Returns
array: The table name and the table alias.
Since
2.0.16
queryScalar()
Section titled “queryScalar() ”protected function queryScalar(mixed $selectExpression, mixed $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 | mixed | |
$db | mixed | The database connection used to execute the query. |
Returns
bool|string|null
Throws
Throwable: if can’t create command