# ActiveQuery

> ActiveQuery represents a DB query associated with an Active Record class.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [db](/docs/api/yii/db/index.md) › ActiveQuery

| class | `yii\db\ActiveQuery` |
| --- | --- |
| Extends | [`Query`](/docs/api/yii/db/query/index.md) » [`yii\base\Component`](/docs/api/yii/base/component/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md), [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md), [`QueryInterface`](/docs/api/yii/db/queryinterface/index.md), [`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) |
| Uses traits | [`ActiveQueryTrait`](/docs/api/yii/db/activequerytrait/index.md), [`ActiveRelationTrait`](/docs/api/yii/db/activerelationtrait/index.md), [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| Since | 2.0 |
| Source | [`framework/db/ActiveQuery.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/db/ActiveQuery.php#L86) |

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()`](/docs/api/yii/db/activerecord/index.md#method-find) and [`ActiveRecord::findBySql()`](/docs/api/yii/db/activerecord/index.md#method-findBySql).
Relational queries are created by [`ActiveRecord::hasOne()`](/docs/api/yii/db/activerecord/index.md#method-hasOne) and [`ActiveRecord::hasMany()`](/docs/api/yii/db/activerecord/index.md#method-hasMany).

Normal Query
------------

ActiveQuery mainly provides the following methods to retrieve the query results:

- [`one()`](/docs/api/yii/db/activequery/index.md#method-one): returns a single record populated with the first row of data.
- [`all()`](/docs/api/yii/db/activequery/index.md#method-all): returns all records based on the query results.
- [`count()`](/docs/api/yii/db/query/index.md#method-count): returns the number of records.
- [`sum()`](/docs/api/yii/db/query/index.md#method-sum): returns the sum over the specified column.
- [`average()`](/docs/api/yii/db/query/index.md#method-average): returns the average over the specified column.
- [`min()`](/docs/api/yii/db/query/index.md#method-min): returns the min over the specified column.
- [`max()`](/docs/api/yii/db/query/index.md#method-max): returns the max over the specified column.
- [`scalar()`](/docs/api/yii/db/query/index.md#method-scalar): returns the value of the first column in the first row of the query result.
- [`column()`](/docs/api/yii/db/query/index.md#method-column): returns the value of the first column in the query result.
- [`exists()`](/docs/api/yii/db/query/index.md#method-exists): returns a value indicating whether the query result has data or not.

Because ActiveQuery extends from [`Query`](/docs/api/yii/db/query/index.md), one can use query methods, such as [`where()`](/docs/api/yii/db/query/index.md#method-where),
[`orderBy()`](/docs/api/yii/db/querytrait/index.md#method-orderBy) to customize the query options.

ActiveQuery also provides the following additional query options:

- [`with()`](/docs/api/yii/db/activequerytrait/index.md#method-with): list of relations that this query should be performed with.
- [`joinWith()`](/docs/api/yii/db/activequery/index.md#method-joinWith): reuse a relation query definition to add a join to a query.
- [`indexBy()`](/docs/api/yii/db/querytrait/index.md#method-indexBy): the name of the column by which the query result should be indexed.
- [`asArray()`](/docs/api/yii/db/activequery/index.md#method-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
----------------

In relational context ActiveQuery represents a relation between two Active Record classes.

Relational ActiveQuery instances are usually created by calling [`ActiveRecord::hasOne()`](/docs/api/yii/db/activerecord/index.md#method-hasOne) and
[`ActiveRecord::hasMany()`](/docs/api/yii/db/activerecord/index.md#method-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`](/docs/api/yii/db/activerelationtrait/index.md#property-link) which represents the association between columns
of different tables; and the multiplicity of the relation is indicated by [`$multiple`](/docs/api/yii/db/activerelationtrait/index.md#property-multiple).

If a relation involves a junction table, it may be specified by [`via()`](/docs/api/yii/db/activerelationtrait/index.md#method-via) or [`viaTable()`](/docs/api/yii/db/activequery/index.md#method-viaTable) method.
These methods may only be called in a relational context. Same is true for [`inverseOf()`](/docs/api/yii/db/activerelationtrait/index.md#method-inverseOf), which
marks a relation as inverse of another relation and [`onCondition()`](/docs/api/yii/db/activequery/index.md#method-onCondition) which adds a condition that
is to be added to relational query join condition.

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="property-asArray"></span>[`$asArray`](/docs/api/yii/db/activequerytrait/index.md#property-asArray) | `bool` | Whether to return each record as an array. Default: `null`. | [`ActiveQueryTrait`](/docs/api/yii/db/activequerytrait/index.md) |
| <span id="property-behaviors"></span>[`$behaviors`](/docs/api/yii/base/component/index.md#property-behaviors) read-only | `array<`[`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md)`<static>>` | List of behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="property-distinct"></span>[`$distinct`](/docs/api/yii/db/query/index.md#property-distinct) | `bool` | Whether to select distinct rows of data only. Default: `false`. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-emulateExecution"></span>[`$emulateExecution`](/docs/api/yii/db/querytrait/index.md#property-emulateExecution) | `bool` | Whether to emulate the actual query execution, returning empty or false results. Default: `false`. Available since 2.0.11. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="property-from"></span>[`$from`](/docs/api/yii/db/query/index.md#property-from) | `array\|string\|null` | The table(s) to be selected from. Default: `null`. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-groupBy"></span>[`$groupBy`](/docs/api/yii/db/query/index.md#property-groupBy) | `array\|null` | How to group the query results. Default: `null`. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-having"></span>[`$having`](/docs/api/yii/db/query/index.md#property-having) | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | The condition to be applied in the GROUP BY clause. Default: `null`. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-indexBy"></span>[`$indexBy`](/docs/api/yii/db/querytrait/index.md#property-indexBy) | `string\|callable\|null` | The name of the column by which the query results should be indexed by. Default: `null`. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="property-inverseOf"></span>[`$inverseOf`](/docs/api/yii/db/activerelationtrait/index.md#property-inverseOf) | `string` | The name of the relation that is the inverse of this relation. Default: `null`. | [`ActiveRelationTrait`](/docs/api/yii/db/activerelationtrait/index.md) |
| <span id="property-join"></span>[`$join`](/docs/api/yii/db/query/index.md#property-join) | `array\|null` | How to join with other tables. Default: `null`. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-joinWith"></span>`$joinWith` | `array\|null` | A list of relations that this query should be joined with Default: `null`. | `ActiveQuery` |
| <span id="property-limit"></span>[`$limit`](/docs/api/yii/db/querytrait/index.md#property-limit) | `int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | Maximum number of records to be returned. Default: `null`. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="property-link"></span>[`$link`](/docs/api/yii/db/activerelationtrait/index.md#property-link) | `array` | The columns of the primary and foreign tables that establish a relation. Default: `null`. | [`ActiveRelationTrait`](/docs/api/yii/db/activerelationtrait/index.md) |
| <span id="property-modelClass"></span>[`$modelClass`](/docs/api/yii/db/activequerytrait/index.md#property-modelClass) | `class-string<`[`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md)`>` | The name of the ActiveRecord class. Default: `null`. | [`ActiveQueryTrait`](/docs/api/yii/db/activequerytrait/index.md) |
| <span id="property-multiple"></span>[`$multiple`](/docs/api/yii/db/activerelationtrait/index.md#property-multiple) | `bool` | Whether this query represents a relation to more than one record. Default: `null`. | [`ActiveRelationTrait`](/docs/api/yii/db/activerelationtrait/index.md) |
| <span id="property-offset"></span>[`$offset`](/docs/api/yii/db/querytrait/index.md#property-offset) | `int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | Zero-based offset from where the records are to be returned. Default: `null`. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`$on`](#property-on) | `string\|array\|null` | The join condition to be used when this query is used in a relational context. Default: `null`. | `ActiveQuery` |
| <span id="property-orderBy"></span>[`$orderBy`](/docs/api/yii/db/querytrait/index.md#property-orderBy) | `array\|null` | How to sort the query results. Default: `null`. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="property-params"></span>[`$params`](/docs/api/yii/db/query/index.md#property-params) | `array\|null` | List of query parameter values indexed by parameter placeholders. Default: `[]`. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-primaryModel"></span>[`$primaryModel`](/docs/api/yii/db/activerelationtrait/index.md#property-primaryModel) | [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) | The primary model of a relational query. Default: `null`. | [`ActiveRelationTrait`](/docs/api/yii/db/activerelationtrait/index.md) |
| <span id="property-queryCacheDependency"></span>[`$queryCacheDependency`](/docs/api/yii/db/query/index.md#property-queryCacheDependency) | [`yii\caching\Dependency`](/docs/api/yii/caching/dependency/index.md)`\|null` | The dependency to be associated with the cached query result for this query Default: `null`. Available since 2.0.14. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-queryCacheDuration"></span>[`$queryCacheDuration`](/docs/api/yii/db/query/index.md#property-queryCacheDuration) | `int\|bool\|null` | The default number of seconds that query results can remain valid in cache. Default: `null`. Available since 2.0.14. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-select"></span>[`$select`](/docs/api/yii/db/query/index.md#property-select) | `array\|null` | The columns being selected. Default: `null`. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-selectOption"></span>[`$selectOption`](/docs/api/yii/db/query/index.md#property-selectOption) | `string\|null` | Additional option that should be appended to the 'SELECT' keyword. Default: `null`. | [`Query`](/docs/api/yii/db/query/index.md) |
| [`$sql`](#property-sql) | `string\|null` | The SQL statement to be executed for retrieving AR records. Default: `null`. | `ActiveQuery` |
| <span id="property-tablesUsedInFrom"></span>[`$tablesUsedInFrom`](/docs/api/yii/db/query/index.md#property-tablesUsedInFrom) read-only | `string[]` | Table names indexed by aliases. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-union"></span>[`$union`](/docs/api/yii/db/query/index.md#property-union) | `array\|null` | This is used to construct the UNION clause(s) in a SQL statement. Default: `null`. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-unionLimit"></span>[`$unionLimit`](/docs/api/yii/db/query/index.md#property-unionLimit) | `int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | Number of records to return from the complete UNION result. Default: `null`. Available since 22.0. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-unionOffset"></span>[`$unionOffset`](/docs/api/yii/db/query/index.md#property-unionOffset) | `int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | Zero-based offset for the complete UNION result. Default: `null`. Available since 22.0. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-unionOrderBy"></span>[`$unionOrderBy`](/docs/api/yii/db/query/index.md#property-unionOrderBy) | `array<int\|string, int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`>\|null` | How to sort the complete UNION result. Default: `null`. Available since 22.0. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="property-via"></span>[`$via`](/docs/api/yii/db/activerelationtrait/index.md#property-via) | `array\|object\|null` | The query associated with the junction table. Default: `null`. | [`ActiveRelationTrait`](/docs/api/yii/db/activerelationtrait/index.md) |
| <span id="property-where"></span>[`$where`](/docs/api/yii/db/querytrait/index.md#property-where) | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | Query condition. Default: `null`. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="property-with"></span>[`$with`](/docs/api/yii/db/activequerytrait/index.md#property-with) | `array\|null` | A list of relations that this query should be performed with Default: `null`. | [`ActiveQueryTrait`](/docs/api/yii/db/activequerytrait/index.md) |
| <span id="property-withQueries"></span>[`$withQueries`](/docs/api/yii/db/query/index.md#property-withQueries) | `array\|null` | This is used to construct the WITH section in a SQL query. Default: `null`. Available since 2.0.35. | [`Query`](/docs/api/yii/db/query/index.md) |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| [`__construct()`](#method-__construct) | Constructor. | `ActiveQuery` |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/component/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__clone"></span>[`__clone()`](/docs/api/yii/base/component/index.md#method-__clone) | This method is called after the object is created by cloning an existing one. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/component/index.md#method-__get) | Returns the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/component/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/component/index.md#method-__set) | Sets the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__toString"></span>[`__toString()`](/docs/api/yii/db/query/index.md#method-__toString) | Returns the SQL representation of Query | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/component/index.md#method-__unset) | Sets a component property to be null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-addGroupBy"></span>[`addGroupBy()`](/docs/api/yii/db/query/index.md#method-addGroupBy) | Adds additional group-by columns to the existing ones. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-addOrderBy"></span>[`addOrderBy()`](/docs/api/yii/db/querytrait/index.md#method-addOrderBy) | Adds additional ORDER BY columns to the query. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-addParams"></span>[`addParams()`](/docs/api/yii/db/query/index.md#method-addParams) | Adds additional parameters to be bound to the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-addSelect"></span>[`addSelect()`](/docs/api/yii/db/query/index.md#method-addSelect) | Add more columns to the SELECT part of the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-addUnionOrderBy"></span>[`addUnionOrderBy()`](/docs/api/yii/db/query/index.md#method-addUnionOrderBy) | Adds ORDER BY columns to the complete UNION result. | [`Query`](/docs/api/yii/db/query/index.md) |
| [`alias()`](#method-alias) | Define an alias for the table defined in [`$modelClass`](/docs/api/yii/db/activequerytrait/index.md#property-modelClass). | `ActiveQuery` |
| [`all()`](#method-all) | Executes query and returns all results as an array. | `ActiveQuery` |
| <span id="method-andFilterCompare"></span>[`andFilterCompare()`](/docs/api/yii/db/query/index.md#method-andFilterCompare) | Adds a filtering condition for a specific column and allow the user to choose a filter operator. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-andFilterHaving"></span>[`andFilterHaving()`](/docs/api/yii/db/query/index.md#method-andFilterHaving) | Adds an additional HAVING condition to the existing one but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-andFilterWhere"></span>[`andFilterWhere()`](/docs/api/yii/db/querytrait/index.md#method-andFilterWhere) | Adds an additional WHERE condition to the existing one but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-andHaving"></span>[`andHaving()`](/docs/api/yii/db/query/index.md#method-andHaving) | Adds an additional HAVING condition to the existing one. | [`Query`](/docs/api/yii/db/query/index.md) |
| [`andOnCondition()`](#method-andOnCondition) | Adds an additional ON condition to the existing one. | `ActiveQuery` |
| <span id="method-andWhere"></span>[`andWhere()`](/docs/api/yii/db/query/index.md#method-andWhere) | Adds an additional WHERE condition to the existing one. | [`Query`](/docs/api/yii/db/query/index.md) |
| [`asArray()`](#method-asArray) | Sets the [`asArray()`](/docs/api/yii/db/activequery/index.md#method-asArray) property. | `ActiveQuery` |
| <span id="method-attachBehavior"></span>[`attachBehavior()`](/docs/api/yii/base/component/index.md#method-attachBehavior) | Attaches a behavior to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehaviors"></span>[`attachBehaviors()`](/docs/api/yii/base/component/index.md#method-attachBehaviors) | Attaches a list of behaviors to the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-average"></span>[`average()`](/docs/api/yii/db/query/index.md#method-average) | Returns the average of the specified column values. | [`Query`](/docs/api/yii/db/query/index.md) |
| [`batch()`](#method-batch) | The batch query result. | `ActiveQuery` |
| <span id="method-behaviors"></span>[`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) | Returns a list of behaviors that this component should behave as. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-cache"></span>[`cache()`](/docs/api/yii/db/query/index.md#method-cache) | Enables query cache for this Query. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/component/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/component/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-column"></span>[`column()`](/docs/api/yii/db/query/index.md#method-column) | Executes the query and returns the first column of the result. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-count"></span>[`count()`](/docs/api/yii/db/query/index.md#method-count) | Returns the number of records. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-create"></span>[`create()`](/docs/api/yii/db/query/index.md#method-create) static | Creates a new Query object and copies its property values from an existing one. | [`Query`](/docs/api/yii/db/query/index.md) |
| [`createCommand()`](#method-createCommand) | Creates a DB command that can be used to execute this query. | `ActiveQuery` |
| <span id="method-detachBehavior"></span>[`detachBehavior()`](/docs/api/yii/base/component/index.md#method-detachBehavior) | Detaches a behavior from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-detachBehaviors"></span>[`detachBehaviors()`](/docs/api/yii/base/component/index.md#method-detachBehaviors) | Detaches all behaviors from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-distinct"></span>[`distinct()`](/docs/api/yii/db/query/index.md#method-distinct) | Sets the value indicating whether to SELECT DISTINCT or not. | [`Query`](/docs/api/yii/db/query/index.md) |
| [`each()`](#method-each) | The batch query result. | `ActiveQuery` |
| <span id="method-emulateExecution"></span>[`emulateExecution()`](/docs/api/yii/db/querytrait/index.md#method-emulateExecution) | Sets whether to emulate query execution, preventing any interaction with data storage. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-ensureBehaviors"></span>[`ensureBehaviors()`](/docs/api/yii/base/component/index.md#method-ensureBehaviors) | Makes sure that the behaviors declared in [`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) are attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-exists"></span>[`exists()`](/docs/api/yii/db/query/index.md#method-exists) | Returns a value indicating whether the query result contains any row of data. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-filterHaving"></span>[`filterHaving()`](/docs/api/yii/db/query/index.md#method-filterHaving) | Sets the HAVING part of the query but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-filterWhere"></span>[`filterWhere()`](/docs/api/yii/db/querytrait/index.md#method-filterWhere) | Sets the WHERE part of the query but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-findFor"></span>[`findFor()`](/docs/api/yii/db/activerelationtrait/index.md#method-findFor) | Finds the related records for the specified primary record. | [`ActiveRelationTrait`](/docs/api/yii/db/activerelationtrait/index.md) |
| <span id="method-findWith"></span>[`findWith()`](/docs/api/yii/db/activequerytrait/index.md#method-findWith) | Finds records corresponding to one or multiple relations and populates them into the primary models. | [`ActiveQueryTrait`](/docs/api/yii/db/activequerytrait/index.md) |
| <span id="method-from"></span>[`from()`](/docs/api/yii/db/query/index.md#method-from) | Sets the FROM part of the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-getBehavior"></span>[`getBehavior()`](/docs/api/yii/base/component/index.md#method-getBehavior) | Returns the named behavior object. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehaviors"></span>[`getBehaviors()`](/docs/api/yii/base/component/index.md#method-getBehaviors) | Returns all behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`getTablesUsedInFrom()`](#method-getTablesUsedInFrom) | Returns table names used in [`from()`](/docs/api/yii/db/query/index.md#method-from) indexed by aliases. | `ActiveQuery` |
| <span id="method-groupBy"></span>[`groupBy()`](/docs/api/yii/db/query/index.md#method-groupBy) | Sets the GROUP BY part of the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-hasEventHandlers"></span>[`hasEventHandlers()`](/docs/api/yii/base/component/index.md#method-hasEventHandlers) | Returns a value indicating whether there is any handler attached to the named event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/component/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/component/index.md#method-hasProperty) | Returns a value indicating whether a property is defined for this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-having"></span>[`having()`](/docs/api/yii/db/query/index.md#method-having) | Sets the HAVING part of the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-indexBy"></span>[`indexBy()`](/docs/api/yii/db/querytrait/index.md#method-indexBy) | Sets the [`indexBy()`](/docs/api/yii/db/querytrait/index.md#method-indexBy) property. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`init()`](#method-init) | Initializes the object. | `ActiveQuery` |
| <span id="method-innerJoin"></span>[`innerJoin()`](/docs/api/yii/db/query/index.md#method-innerJoin) | Appends an INNER JOIN part to the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| [`innerJoinWith()`](#method-innerJoinWith) | Inner joins with the specified relations. | `ActiveQuery` |
| <span id="method-inverseOf"></span>[`inverseOf()`](/docs/api/yii/db/activerelationtrait/index.md#method-inverseOf) | Sets the name of the relation that is the inverse of this relation. | [`ActiveRelationTrait`](/docs/api/yii/db/activerelationtrait/index.md) |
| <span id="method-join"></span>[`join()`](/docs/api/yii/db/query/index.md#method-join) | Appends a JOIN part to the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| [`joinWith()`](#method-joinWith) | Joins with the specified relations. | `ActiveQuery` |
| <span id="method-leftJoin"></span>[`leftJoin()`](/docs/api/yii/db/query/index.md#method-leftJoin) | Appends a LEFT OUTER JOIN part to the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-limit"></span>[`limit()`](/docs/api/yii/db/querytrait/index.md#method-limit) | Sets the LIMIT part of the query. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-max"></span>[`max()`](/docs/api/yii/db/query/index.md#method-max) | Returns the maximum of the specified column values. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-min"></span>[`min()`](/docs/api/yii/db/query/index.md#method-min) | Returns the minimum of the specified column values. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-noCache"></span>[`noCache()`](/docs/api/yii/db/query/index.md#method-noCache) | Disables query cache for this Query. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-off"></span>[`off()`](/docs/api/yii/base/component/index.md#method-off) | Detaches an existing event handler from this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-offset"></span>[`offset()`](/docs/api/yii/db/querytrait/index.md#method-offset) | Sets the OFFSET part of the query. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-on"></span>[`on()`](/docs/api/yii/base/component/index.md#method-on) | Attaches an event handler to an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`onCondition()`](#method-onCondition) | Sets the ON condition for a relational query. | `ActiveQuery` |
| [`one()`](#method-one) | Executes query and returns a single row of result. | `ActiveQuery` |
| <span id="method-orderBy"></span>[`orderBy()`](/docs/api/yii/db/querytrait/index.md#method-orderBy) | Sets the ORDER BY part of the query. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-orFilterHaving"></span>[`orFilterHaving()`](/docs/api/yii/db/query/index.md#method-orFilterHaving) | Adds an additional HAVING condition to the existing one but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-orFilterWhere"></span>[`orFilterWhere()`](/docs/api/yii/db/querytrait/index.md#method-orFilterWhere) | Adds an additional WHERE condition to the existing one but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-orHaving"></span>[`orHaving()`](/docs/api/yii/db/query/index.md#method-orHaving) | Adds an additional HAVING condition to the existing one. | [`Query`](/docs/api/yii/db/query/index.md) |
| [`orOnCondition()`](#method-orOnCondition) | Adds an additional ON condition to the existing one. | `ActiveQuery` |
| <span id="method-orWhere"></span>[`orWhere()`](/docs/api/yii/db/query/index.md#method-orWhere) | Adds an additional WHERE condition to the existing one. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-params"></span>[`params()`](/docs/api/yii/db/query/index.md#method-params) | Sets the parameters to be bound to the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| [`populate()`](#method-populate) | Converts the raw query results into the format as specified by this query. | `ActiveQuery` |
| <span id="method-populateRelation"></span>[`populateRelation()`](/docs/api/yii/db/activerelationtrait/index.md#method-populateRelation) | Finds the related records and populates them into the primary models. | [`ActiveRelationTrait`](/docs/api/yii/db/activerelationtrait/index.md) |
| [`prepare()`](#method-prepare) | Prepares for building SQL. | `ActiveQuery` |
| <span id="method-rightJoin"></span>[`rightJoin()`](/docs/api/yii/db/query/index.md#method-rightJoin) | Appends a RIGHT OUTER JOIN part to the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-scalar"></span>[`scalar()`](/docs/api/yii/db/query/index.md#method-scalar) | Returns the query result as a scalar value. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-select"></span>[`select()`](/docs/api/yii/db/query/index.md#method-select) | Sets the SELECT part of the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-sum"></span>[`sum()`](/docs/api/yii/db/query/index.md#method-sum) | Returns the sum of the specified column values. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-trigger"></span>[`trigger()`](/docs/api/yii/base/component/index.md#method-trigger) | Triggers an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-union"></span>[`union()`](/docs/api/yii/db/query/index.md#method-union) | Appends a SQL statement using UNION operator. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-unionLimit"></span>[`unionLimit()`](/docs/api/yii/db/query/index.md#method-unionLimit) | Sets the LIMIT part of the complete UNION result. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-unionOffset"></span>[`unionOffset()`](/docs/api/yii/db/query/index.md#method-unionOffset) | Sets the OFFSET part of the complete UNION result. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-unionOrderBy"></span>[`unionOrderBy()`](/docs/api/yii/db/query/index.md#method-unionOrderBy) | Sets the ORDER BY part of the complete UNION result. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-via"></span>[`via()`](/docs/api/yii/db/activerelationtrait/index.md#method-via) | Specifies the relation associated with the junction table. | [`ActiveRelationTrait`](/docs/api/yii/db/activerelationtrait/index.md) |
| [`viaTable()`](#method-viaTable) | Specifies the junction table for a relational query. | `ActiveQuery` |
| <span id="method-where"></span>[`where()`](/docs/api/yii/db/query/index.md#method-where) | Sets the WHERE part of the query. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-with"></span>[`with()`](/docs/api/yii/db/activequerytrait/index.md#method-with) | Specifies the relations with which this query should be performed. | [`ActiveQueryTrait`](/docs/api/yii/db/activequerytrait/index.md) |
| <span id="method-withQuery"></span>[`withQuery()`](/docs/api/yii/db/query/index.md#method-withQuery) | Prepends a SQL statement using WITH syntax. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-cleanUpTableNames"></span>[`cleanUpTableNames()`](/docs/api/yii/db/query/index.md#method-cleanUpTableNames) protected | Clean up table names and aliases Both aliases and names are enclosed into {{ and }}. | [`Query`](/docs/api/yii/db/query/index.md) |
| <span id="method-createModels"></span>[`createModels()`](/docs/api/yii/db/activequerytrait/index.md#method-createModels) protected | Converts found rows into model instances. | [`ActiveQueryTrait`](/docs/api/yii/db/activequerytrait/index.md) |
| <span id="method-filterCondition"></span>[`filterCondition()`](/docs/api/yii/db/querytrait/index.md#method-filterCondition) protected | Removes [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty) from the given query condition. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`getPrimaryTableName()`](#method-getPrimaryTableName) protected |  | `ActiveQuery` |
| [`getTableNameAndAlias()`](#method-getTableNameAndAlias) protected | Returns the table name and the table alias for [`$modelClass`](/docs/api/yii/db/activequerytrait/index.md#property-modelClass). | `ActiveQuery` |
| <span id="method-isEmpty"></span>[`isEmpty()`](/docs/api/yii/db/querytrait/index.md#method-isEmpty) protected | Returns a value indicating whether the give value is "empty". | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-normalizeOrderBy"></span>[`normalizeOrderBy()`](/docs/api/yii/db/querytrait/index.md#method-normalizeOrderBy) protected | Normalizes format of ORDER BY data. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-normalizeSelect"></span>[`normalizeSelect()`](/docs/api/yii/db/query/index.md#method-normalizeSelect) protected | Normalizes the SELECT columns passed to [`select()`](/docs/api/yii/db/query/index.md#method-select) or [`addSelect()`](/docs/api/yii/db/query/index.md#method-addSelect). | [`Query`](/docs/api/yii/db/query/index.md) |
| [`queryScalar()`](#method-queryScalar) protected | Queries a scalar value by setting [`select()`](/docs/api/yii/db/query/index.md#method-select) first. | `ActiveQuery` |
| <span id="method-setCommandCache"></span>[`setCommandCache()`](/docs/api/yii/db/query/index.md#method-setCommandCache) protected | Sets $command cache, if this query has enabled caching. | [`Query`](/docs/api/yii/db/query/index.md) |

## Events

| Event | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="event-EVENT_INIT"></span>`EVENT_INIT` | `yii\db\Event` | An event that is triggered when the query is initialized via [`init()`](/docs/api/yii/db/activequery/index.md#method-init). Event name: `'init'`. | `ActiveQuery` |

## Property details

### $on <span id="property-on"></span>

```php
public string|array|null $on = null
```

The 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()`](/docs/api/yii/db/activequery/index.md#method-joinWith) is called.
Otherwise, the condition will be used in the WHERE part of a query.
Please refer to [`Query::where()`](/docs/api/yii/db/query/index.md#method-where) on how to specify this parameter.

### $sql <span id="property-sql"></span>

```php
public string|null $sql = null
```

The SQL statement to be executed for retrieving AR records.

This is set by [`ActiveRecord::findBySql()`](/docs/api/yii/db/activerecord/index.md#method-findBySql).

## Method details

### __construct() <span id="method-__construct"></span>

```php
public function __construct(class-string<yii\db\ActiveRecordInterface> $modelClass, array $config = [])
```

Constructor.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$modelClass` | `class-string<`[`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md)`>` | The model class associated with this query |
| `$config` | `array` | Configurations to be applied to the newly created query object |

### alias() <span id="method-alias"></span>

```php
public function alias(string $alias): $this
```

Define an alias for the table defined in [`$modelClass`](/docs/api/yii/db/activequerytrait/index.md#property-modelClass).

This method will adjust [`from()`](/docs/api/yii/db/query/index.md#method-from) so that an already defined alias will be overwritten.
If none was defined, [`from()`](/docs/api/yii/db/query/index.md#method-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() <span id="method-all"></span>

```php
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`](/docs/api/yii/db/connection/index.md)`\|null` | The DB connection used to create the DB command. If null, the DB connection returned by [`$modelClass`](/docs/api/yii/db/activequerytrait/index.md#property-modelClass) will be used. |

**Returns**

`yii\db\T[]`: The query results. If the query results in nothing, an empty array will be returned.

### andOnCondition() <span id="method-andOnCondition"></span>

```php
public function andOnCondition(string|array $condition, array $params = []): $this
```

Adds 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\|array` | The new ON condition. Please refer to [`where()`](/docs/api/yii/db/query/index.md#method-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**

- [`onCondition()`](/docs/api/yii/db/activequery/index.md#method-onCondition)
- [`orOnCondition()`](/docs/api/yii/db/activequery/index.md#method-orOnCondition)

### asArray() <span id="method-asArray"></span>

```php
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()`](/docs/api/yii/db/activequery/index.md#method-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() <span id="method-batch"></span>

```php
public function batch(mixed $batchSize, mixed $db): yii\db\BatchQueryResult<int, yii\db\T[]>
```

The batch query result.

It implements the [`Iterator`](https://www.php.net/manual/en/class.iterator.php) interface
and can be traversed to retrieve the data in batches.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$batchSize` | `mixed` |  |
| `$db` | `mixed` |  |

**Returns**

[`BatchQueryResult`](/docs/api/yii/db/batchqueryresult/index.md)`<int, yii\db\T[]>`

### createCommand() <span id="method-createCommand"></span>

```php
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**

| Parameter | Type | Description |
| --- | --- | --- |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The DB connection used to create the DB command. If `null`, the DB connection returned by [`$modelClass`](/docs/api/yii/db/activequerytrait/index.md#property-modelClass) will be used. |

**Returns**

[`Command`](/docs/api/yii/db/command/index.md): The created DB command instance.

### each() <span id="method-each"></span>

```php
public function each(mixed $batchSize, mixed $db): yii\db\BatchQueryResult<array-key, yii\db\T>
```

The batch query result.

It implements the [`Iterator`](https://www.php.net/manual/en/class.iterator.php) interface
and can be traversed to retrieve the data in batches.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$batchSize` | `mixed` |  |
| `$db` | `mixed` |  |

**Returns**

[`BatchQueryResult`](/docs/api/yii/db/batchqueryresult/index.md)`<array-key, yii\db\T>`

### getTablesUsedInFrom() <span id="method-getTablesUsedInFrom"></span>

```php
public function getTablesUsedInFrom(): string[]
```

Returns table names used in [`from()`](/docs/api/yii/db/query/index.md#method-from) indexed by aliases.

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

**Returns**

`string[]`: Table names indexed by aliases

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md)

**Since**

2.0.12

### init() <span id="method-init"></span>

```php
public function init(): mixed
```

Initializes the object.

This method is called at the end of the constructor. The default implementation will trigger
an [`EVENT_INIT`](/docs/api/yii/db/activequery/index.md#event-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() <span id="method-innerJoinWith"></span>

```php
public function innerJoinWith(string|array $with, bool|array $eagerLoading = true): $this
```

Inner joins with the specified relations.

This is a shortcut method to [`joinWith()`](/docs/api/yii/db/activequery/index.md#method-joinWith) with the join type set as "INNER JOIN".
Please refer to [`joinWith()`](/docs/api/yii/db/activequery/index.md#method-joinWith) for detailed usage of this method.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$with` | `string\|array` | The relations to be joined with. |
| `$eagerLoading` | `bool\|array` | 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()`](/docs/api/yii/db/activequery/index.md#method-joinWith)

### joinWith() <span id="method-joinWith"></span>

```php
public function joinWith(string|array $with, bool|array $eagerLoading = true, string|array $joinType = 'LEFT JOIN'): $this
```

Joins 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()`](/docs/api/yii/db/activequerytrait/index.md#method-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()`](/docs/api/yii/db/activequerytrait/index.md#method-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()`](/docs/api/yii/db/activequerytrait/index.md#method-with) in addition with the specified relations.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$with` | `string\|array` | 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()`](/docs/api/yii/db/activequerytrait/index.md#method-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\|array` | 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\|array` | 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() <span id="method-onCondition"></span>

```php
public function onCondition(string|array $condition, array $params = []): $this
```

Sets the ON condition for a relational query.

The condition will be used in the ON part when [`ActiveQuery::joinWith()`](/docs/api/yii/db/activequery/index.md#method-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`](/docs/api/yii/db/activerecord/index.md) 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\|array` | The ON condition. Please refer to [`Query::where()`](/docs/api/yii/db/query/index.md#method-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() <span id="method-one"></span>

```php
public function one(yii\db\Connection|null $db = null): yii\db\T|null
```

Executes query and returns a single row of result.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The DB connection used to create the DB command. If `null`, the DB connection returned by [`$modelClass`](/docs/api/yii/db/activequerytrait/index.md#property-modelClass) will be used. |

**Returns**

`yii\db\T|null`: A single row of query result. Depending on the setting of [`asArray()`](/docs/api/yii/db/activequery/index.md#method-asArray), the query result may be either an array or an ActiveRecord object. `null` will be returned if the query results in nothing.

### orOnCondition() <span id="method-orOnCondition"></span>

```php
public function orOnCondition(string|array $condition, array $params = []): $this
```

Adds 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\|array` | The new ON condition. Please refer to [`where()`](/docs/api/yii/db/query/index.md#method-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**

- [`onCondition()`](/docs/api/yii/db/activequery/index.md#method-onCondition)
- [`andOnCondition()`](/docs/api/yii/db/activequery/index.md#method-andOnCondition)

### populate() <span id="method-populate"></span>

```php
public function populate(mixed $rows, mixed $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**

| 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() <span id="method-prepare"></span>

```php
public function prepare(mixed $builder): self
```

Prepares for building SQL.

This method is called by [`QueryBuilder`](/docs/api/yii/db/querybuilder/index.md) 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`](/docs/api/yii/db/querybuilder/index.md) to build the SQL

### viaTable() <span id="method-viaTable"></span>

```php
public function viaTable(string $tableName, array $link, callable|null $callable = null): $this
```

Specifies the junction table for a relational query.

Use this method to specify a junction table when declaring a relation in the [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) 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`](/docs/api/yii/db/activerelationtrait/index.md#property-primaryModel). The keys of the array represent the columns in the junction table, and the values represent the columns in the [`$primaryModel`](/docs/api/yii/db/activerelationtrait/index.md#property-primaryModel) table. |
| `$callable` | `callable\|null` | 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`](/docs/api/yii/base/invalidconfigexception/index.md): when query is not initialized properly

**See also**

- [`via()`](/docs/api/yii/db/activerelationtrait/index.md#method-via)

### getPrimaryTableName() <span id="method-getPrimaryTableName"></span>

```php
protected function getPrimaryTableName(): string
```

**Returns**

`string`: Primary table name

**Since**

2.0.12

### getTableNameAndAlias() <span id="method-getTableNameAndAlias"></span>

```php
protected function getTableNameAndAlias(): array
```

Returns the table name and the table alias for [`$modelClass`](/docs/api/yii/db/activequerytrait/index.md#property-modelClass).

**Returns**

`array`: The table name and the table alias.

**Since**

2.0.16

### queryScalar() <span id="method-queryScalar"></span>

```php
protected function queryScalar(mixed $selectExpression, mixed $db): bool|string|null
```

Queries a scalar value by setting [`select()`](/docs/api/yii/db/query/index.md#method-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`](https://www.php.net/manual/en/class.throwable.php): if can't create command