# ActiveRecord

> ActiveRecord is the base class for classes representing relational data in terms of objects.

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

| class | `yii\db\ActiveRecord` |
| --- | --- |
| Extends | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) » [`yii\base\Model`](/docs/api/yii/base/model/index.md) » [`yii\base\Component`](/docs/api/yii/base/component/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\StaticInstanceInterface`](/docs/api/yii/base/staticinstanceinterface/index.md), [`IteratorAggregate`](https://www.php.net/manual/en/class.iteratoraggregate.php), [`ArrayAccess`](https://www.php.net/manual/en/class.arrayaccess.php), [`yii\base\Arrayable`](/docs/api/yii/base/arrayable/index.md), [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md), [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md) |
| Uses traits | [`yii\base\ArrayableTrait`](/docs/api/yii/base/arrayabletrait/index.md), [`yii\base\StaticInstanceTrait`](/docs/api/yii/base/staticinstancetrait/index.md) |
| Since | 2.0 |
| Source | [`framework/db/ActiveRecord.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/db/ActiveRecord.php#L78) |

ActiveRecord is the base class for classes representing relational data in terms of objects.

Active Record implements the [Active Record design pattern](https://en.wikipedia.org/wiki/Active_record_pattern).
The premise behind Active Record is that an individual [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) object is associated with a specific
row in a database table. The object's attributes are mapped to the columns of the corresponding table.
Referencing an Active Record attribute is equivalent to accessing the corresponding table column for that record.

As an example, say that the `Customer` ActiveRecord class is associated with the `customer` table.
This would mean that the class's `name` attribute is automatically mapped to the `name` column in `customer` table.
Thanks to Active Record, assuming the variable `$customer` is an object of type `Customer`, to get the value of
the `name` column for the table row, you can use the expression `$customer->name`.
In this example, Active Record is providing an object-oriented interface for accessing data stored in the database.
But Active Record provides much more functionality than this.

To declare an ActiveRecord class you need to extend [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) and
implement the `tableName` method:

```
<?php

class Customer extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'customer';
    }
}
```

The `tableName` method only has to return the name of the database table associated with the class.

> Tip: You may also use the [Gii code generator](/docs/guide/start-gii/index.md) to generate ActiveRecord classes from your
> database tables.

Class instances are obtained in one of two ways:

* Using the `new` operator to create a new, empty object
* Using a method to fetch an existing record (or records) from the database

Below is an example showing some typical usage of ActiveRecord:

```
$user = new User();
$user->name = 'Qiang';
$user->save();  // a new row is inserted into user table

// the following will retrieve the user 'CeBe' from the database
$user = User::find()->where(['name' => 'CeBe'])->one();

// this will get related records from orders table when relation is defined
$orders = $user->orders;
```

For more details and usage information on ActiveRecord, see the [guide article on ActiveRecord](/docs/guide/db-active-record/index.md).

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="property-activeValidators"></span>[`$activeValidators`](/docs/api/yii/base/model/index.md#property-activeValidators) read-only | [`yii\validators\Validator`](/docs/api/yii/validators/validator/index.md)`[]` | The validators applicable to the current [`$scenario`](/docs/api/yii/base/model/index.md#property-scenario). | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="property-attributes"></span>[`$attributes`](/docs/api/yii/base/model/index.md#property-attributes) | `array<string, mixed>` | Attribute values (name => value). | [`yii\base\Model`](/docs/api/yii/base/model/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-dirtyAttributes"></span>[`$dirtyAttributes`](/docs/api/yii/db/baseactiverecord/index.md#property-dirtyAttributes) read-only | `array` | The changed attribute values (name-value pairs). | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="property-errors"></span>[`$errors`](/docs/api/yii/base/model/index.md#property-errors) read-only | `array<string, string[]>` | Errors for all attributes. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="property-firstErrors"></span>[`$firstErrors`](/docs/api/yii/base/model/index.md#property-firstErrors) read-only | `array<string, string>` | The first errors. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="property-isNewRecord"></span>[`$isNewRecord`](/docs/api/yii/db/baseactiverecord/index.md#property-isNewRecord) | `bool` | Whether the record is new and should be inserted when calling [`save()`](/docs/api/yii/db/baseactiverecord/index.md#method-save). | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="property-iterator"></span>[`$iterator`](/docs/api/yii/base/model/index.md#property-iterator) read-only | [`ArrayIterator`](https://www.php.net/manual/en/class.arrayiterator.php)`<string, mixed>` | An iterator for traversing the items in the list. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="property-oldAttributes"></span>[`$oldAttributes`](/docs/api/yii/db/baseactiverecord/index.md#property-oldAttributes) | `array\|null` | Old attribute values to be set. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="property-oldPrimaryKey"></span>[`$oldPrimaryKey`](/docs/api/yii/db/baseactiverecord/index.md#property-oldPrimaryKey) read-only | `mixed` | The old primary key value. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="property-primaryKey"></span>[`$primaryKey`](/docs/api/yii/db/baseactiverecord/index.md#property-primaryKey) read-only | `mixed` | The primary key value. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="property-relatedRecords"></span>[`$relatedRecords`](/docs/api/yii/db/baseactiverecord/index.md#property-relatedRecords) read-only | `array` | An array of related records indexed by relation names. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="property-scenario"></span>[`$scenario`](/docs/api/yii/base/model/index.md#property-scenario) | `string` | The scenario that this model is in. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="property-validators"></span>[`$validators`](/docs/api/yii/base/model/index.md#property-validators) read-only | [`ArrayObject`](https://www.php.net/manual/en/class.arrayobject.php)`<int,` [`yii\validators\Validator`](/docs/api/yii/validators/validator/index.md)`>\|`[`yii\validators\Validator`](/docs/api/yii/validators/validator/index.md)`[]` | All the validators declared in the model. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <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/model/index.md#method-__clone) | This method is called after the object is created by cloning an existing one. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/db/baseactiverecord/index.md#method-__get) | PHP getter magic method. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/db/baseactiverecord/index.md#method-__isset) | Checks if a property value is null. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/db/baseactiverecord/index.md#method-__set) | PHP setter magic method. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/db/baseactiverecord/index.md#method-__unset) | Sets a component property to be null. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-activeAttributes"></span>[`activeAttributes()`](/docs/api/yii/base/model/index.md#method-activeAttributes) | Returns the attribute names that are subject to validation in the current scenario. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-addError"></span>[`addError()`](/docs/api/yii/base/model/index.md#method-addError) | Adds a new error to the specified attribute. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-addErrors"></span>[`addErrors()`](/docs/api/yii/base/model/index.md#method-addErrors) | Adds a list of errors. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-afterDelete"></span>[`afterDelete()`](/docs/api/yii/db/baseactiverecord/index.md#method-afterDelete) | This method is invoked after deleting a record. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-afterFind"></span>[`afterFind()`](/docs/api/yii/db/baseactiverecord/index.md#method-afterFind) | This method is called when the AR object is created and populated with the query result. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-afterRefresh"></span>[`afterRefresh()`](/docs/api/yii/db/baseactiverecord/index.md#method-afterRefresh) | This method is called when the AR object is refreshed. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-afterSave"></span>[`afterSave()`](/docs/api/yii/db/baseactiverecord/index.md#method-afterSave) | This method is called at the end of inserting or updating a record. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-afterValidate"></span>[`afterValidate()`](/docs/api/yii/base/model/index.md#method-afterValidate) | This method is invoked after validation ends. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <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-attributeHints"></span>[`attributeHints()`](/docs/api/yii/base/model/index.md#method-attributeHints) | Returns the attribute hints. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-attributeLabels"></span>[`attributeLabels()`](/docs/api/yii/base/model/index.md#method-attributeLabels) | Returns the attribute labels. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| [`attributes()`](#method-attributes) | Returns the list of all attribute names of the model. | `ActiveRecord` |
| <span id="method-beforeDelete"></span>[`beforeDelete()`](/docs/api/yii/db/baseactiverecord/index.md#method-beforeDelete) | This method is invoked before deleting a record. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-beforeSave"></span>[`beforeSave()`](/docs/api/yii/db/baseactiverecord/index.md#method-beforeSave) | This method is called at the beginning of inserting or updating a record. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-beforeValidate"></span>[`beforeValidate()`](/docs/api/yii/base/model/index.md#method-beforeValidate) | This method is invoked before validation starts. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <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-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/db/baseactiverecord/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-canSetOldAttribute"></span>[`canSetOldAttribute()`](/docs/api/yii/db/baseactiverecord/index.md#method-canSetOldAttribute) | Returns if the old named attribute can be set. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/db/baseactiverecord/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/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-clearErrors"></span>[`clearErrors()`](/docs/api/yii/base/model/index.md#method-clearErrors) | Removes errors for all attributes or a single attribute. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-createValidators"></span>[`createValidators()`](/docs/api/yii/base/model/index.md#method-createValidators) | Creates validator objects based on the validation rules specified in [`rules()`](/docs/api/yii/base/model/index.md#method-rules). | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| [`delete()`](#method-delete) | Deletes the table row corresponding to this active record. | `ActiveRecord` |
| [`deleteAll()`](#method-deleteAll) static | Deletes rows in the table using the provided conditions. | `ActiveRecord` |
| <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-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) |
| [`equals()`](#method-equals) | Returns a value indicating whether the given active record is the same as the current one. | `ActiveRecord` |
| <span id="method-extraFields"></span>[`extraFields()`](/docs/api/yii/db/baseactiverecord/index.md#method-extraFields) | Returns the list of fields that can be expanded further and returned by [`toArray()`](/docs/api/yii/base/arrayabletrait/index.md#method-toArray). | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-fields"></span>[`fields()`](/docs/api/yii/db/baseactiverecord/index.md#method-fields) | Returns the list of fields that should be returned by default by [`toArray()`](/docs/api/yii/base/arrayabletrait/index.md#method-toArray) when no specific fields are specified. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| [`find()`](#method-find) static | Creates an [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md) instance for query purpose. | `ActiveRecord` |
| <span id="method-findAll"></span>[`findAll()`](/docs/api/yii/db/baseactiverecord/index.md#method-findAll) static | Returns a list of active record models that match the specified primary key value(s) or a set of column values. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| [`findBySql()`](#method-findBySql) static | Creates an [`ActiveQuery`](/docs/api/yii/db/activequery/index.md) instance with a given SQL statement. | `ActiveRecord` |
| <span id="method-findOne"></span>[`findOne()`](/docs/api/yii/db/baseactiverecord/index.md#method-findOne) static | Returns a single active record model instance by a primary key or an array of column values. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-formName"></span>[`formName()`](/docs/api/yii/base/model/index.md#method-formName) | Returns the form name that this model class should use. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-generateAttributeLabel"></span>[`generateAttributeLabel()`](/docs/api/yii/base/model/index.md#method-generateAttributeLabel) | Generates a user friendly attribute label based on the give attribute name. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-getActiveValidators"></span>[`getActiveValidators()`](/docs/api/yii/base/model/index.md#method-getActiveValidators) | Returns the validators applicable to the current [`$scenario`](/docs/api/yii/base/model/index.md#property-scenario). | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-getAttribute"></span>[`getAttribute()`](/docs/api/yii/db/baseactiverecord/index.md#method-getAttribute) | Returns the named attribute value. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-getAttributeHint"></span>[`getAttributeHint()`](/docs/api/yii/db/baseactiverecord/index.md#method-getAttributeHint) | Returns the text hint for the specified attribute. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-getAttributeLabel"></span>[`getAttributeLabel()`](/docs/api/yii/db/baseactiverecord/index.md#method-getAttributeLabel) | Returns the text label for the specified attribute. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-getAttributes"></span>[`getAttributes()`](/docs/api/yii/base/model/index.md#method-getAttributes) | Returns attribute values. | [`yii\base\Model`](/docs/api/yii/base/model/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) |
| [`getDb()`](#method-getDb) static | Returns the database connection used by this AR class. | `ActiveRecord` |
| <span id="method-getDirtyAttributes"></span>[`getDirtyAttributes()`](/docs/api/yii/db/baseactiverecord/index.md#method-getDirtyAttributes) | Returns the attribute values that have been modified since they are loaded or saved most recently. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-getErrors"></span>[`getErrors()`](/docs/api/yii/base/model/index.md#method-getErrors) | Returns the errors for all attributes or a single attribute. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-getErrorSummary"></span>[`getErrorSummary()`](/docs/api/yii/base/model/index.md#method-getErrorSummary) | Returns the errors for all attributes as a one-dimensional array. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-getFirstError"></span>[`getFirstError()`](/docs/api/yii/base/model/index.md#method-getFirstError) | Returns the first error of the specified attribute. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-getFirstErrors"></span>[`getFirstErrors()`](/docs/api/yii/base/model/index.md#method-getFirstErrors) | Returns the first error of every attribute in the model. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-getIsNewRecord"></span>[`getIsNewRecord()`](/docs/api/yii/db/baseactiverecord/index.md#method-getIsNewRecord) | Returns a value indicating whether the current record is new. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-getIterator"></span>[`getIterator()`](/docs/api/yii/base/model/index.md#method-getIterator) | Returns an iterator for traversing the attributes in the model. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-getOldAttribute"></span>[`getOldAttribute()`](/docs/api/yii/db/baseactiverecord/index.md#method-getOldAttribute) | Returns the old value of the named attribute. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-getOldAttributes"></span>[`getOldAttributes()`](/docs/api/yii/db/baseactiverecord/index.md#method-getOldAttributes) | Returns the old attribute values. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-getOldPrimaryKey"></span>[`getOldPrimaryKey()`](/docs/api/yii/db/baseactiverecord/index.md#method-getOldPrimaryKey) | Returns the old primary key value(s). | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-getPrimaryKey"></span>[`getPrimaryKey()`](/docs/api/yii/db/baseactiverecord/index.md#method-getPrimaryKey) | Returns the primary key value(s). | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-getRelatedRecords"></span>[`getRelatedRecords()`](/docs/api/yii/db/baseactiverecord/index.md#method-getRelatedRecords) | Returns all populated related records. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-getRelation"></span>[`getRelation()`](/docs/api/yii/db/baseactiverecord/index.md#method-getRelation) | Returns the relation object with the specified name. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-getScenario"></span>[`getScenario()`](/docs/api/yii/base/model/index.md#method-getScenario) | Returns the scenario that this model is used in. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| [`getTableSchema()`](#method-getTableSchema) static | Returns the schema information of the DB table associated with this AR class. | `ActiveRecord` |
| <span id="method-getValidators"></span>[`getValidators()`](/docs/api/yii/base/model/index.md#method-getValidators) | Returns all the validators declared in [`rules()`](/docs/api/yii/base/model/index.md#method-rules). | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-hasAttribute"></span>[`hasAttribute()`](/docs/api/yii/db/baseactiverecord/index.md#method-hasAttribute) | Returns a value indicating whether the model has an attribute with the specified name. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-hasErrors"></span>[`hasErrors()`](/docs/api/yii/base/model/index.md#method-hasErrors) | Returns a value indicating whether there is any validation error. | [`yii\base\Model`](/docs/api/yii/base/model/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) |
| [`hasMany()`](#method-hasMany) | Declares a `has-many` relation. | `ActiveRecord` |
| <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) |
| [`hasOne()`](#method-hasOne) | Declares a `has-one` relation. | `ActiveRecord` |
| <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-init"></span>[`init()`](/docs/api/yii/db/baseactiverecord/index.md#method-init) | Initializes the object. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| [`insert()`](#method-insert) | Inserts a row into the associated database table using the attribute values of this record. | `ActiveRecord` |
| <span id="method-instance"></span>[`instance()`](/docs/api/yii/base/staticinstancetrait/index.md#method-instance) static | Returns static class instance, which can be used to obtain meta information. | [`yii\base\StaticInstanceTrait`](/docs/api/yii/base/staticinstancetrait/index.md) |
| <span id="method-instantiate"></span>[`instantiate()`](/docs/api/yii/db/baseactiverecord/index.md#method-instantiate) static | Creates an active record instance. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-isAttributeActive"></span>[`isAttributeActive()`](/docs/api/yii/base/model/index.md#method-isAttributeActive) | Returns a value indicating whether the attribute is active in the current scenario. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-isAttributeChanged"></span>[`isAttributeChanged()`](/docs/api/yii/db/baseactiverecord/index.md#method-isAttributeChanged) | Returns a value indicating whether the named attribute has been changed. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-isAttributeRequired"></span>[`isAttributeRequired()`](/docs/api/yii/base/model/index.md#method-isAttributeRequired) | Returns a value indicating whether the attribute is required. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-isAttributeSafe"></span>[`isAttributeSafe()`](/docs/api/yii/base/model/index.md#method-isAttributeSafe) | Returns a value indicating whether the attribute is safe for massive assignments. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-isPrimaryKey"></span>[`isPrimaryKey()`](/docs/api/yii/db/baseactiverecord/index.md#method-isPrimaryKey) static | Returns a value indicating whether the given set of attributes represents the primary key for this model. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-isRelationPopulated"></span>[`isRelationPopulated()`](/docs/api/yii/db/baseactiverecord/index.md#method-isRelationPopulated) | Check whether the named relation has been populated with records. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| [`isTransactional()`](#method-isTransactional) | Returns a value indicating whether the specified operation is transactional in the current [`$scenario`](/docs/api/yii/base/model/index.md#property-scenario). | `ActiveRecord` |
| <span id="method-link"></span>[`link()`](/docs/api/yii/db/baseactiverecord/index.md#method-link) | Establishes the relationship between two models. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-load"></span>[`load()`](/docs/api/yii/base/model/index.md#method-load) | Populates the model with input data. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| [`loadDefaultValues()`](#method-loadDefaultValues) | Loads default values from database table schema. | `ActiveRecord` |
| <span id="method-loadMultiple"></span>[`loadMultiple()`](/docs/api/yii/base/model/index.md#method-loadMultiple) static | Populates a set of models with the data from end user. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-loadRelations"></span>[`loadRelations()`](/docs/api/yii/db/baseactiverecord/index.md#method-loadRelations) | Eager loads related models for the already loaded primary model. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-loadRelationsFor"></span>[`loadRelationsFor()`](/docs/api/yii/db/baseactiverecord/index.md#method-loadRelationsFor) static | Eager loads related models for the already loaded primary models. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-markAttributeDirty"></span>[`markAttributeDirty()`](/docs/api/yii/db/baseactiverecord/index.md#method-markAttributeDirty) | Marks an attribute dirty. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/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-offsetExists"></span>[`offsetExists()`](/docs/api/yii/db/baseactiverecord/index.md#method-offsetExists) | Returns whether there is an element at the specified offset. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-offsetGet"></span>[`offsetGet()`](/docs/api/yii/base/model/index.md#method-offsetGet) | Returns the element at the specified offset. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-offsetSet"></span>[`offsetSet()`](/docs/api/yii/base/model/index.md#method-offsetSet) | Sets the element at the specified offset. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-offsetUnset"></span>[`offsetUnset()`](/docs/api/yii/db/baseactiverecord/index.md#method-offsetUnset) | Sets the element value at the specified offset to null. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/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) |
| <span id="method-onUnsafeAttribute"></span>[`onUnsafeAttribute()`](/docs/api/yii/base/model/index.md#method-onUnsafeAttribute) | This method is invoked when an unsafe attribute is being massively assigned. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-optimisticLock"></span>[`optimisticLock()`](/docs/api/yii/db/baseactiverecord/index.md#method-optimisticLock) | Returns the name of the column that stores the lock version for implementing optimistic locking. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| [`populateRecord()`](#method-populateRecord) static | Populates an active record object using a row of data from the database/storage. | `ActiveRecord` |
| <span id="method-populateRelation"></span>[`populateRelation()`](/docs/api/yii/db/baseactiverecord/index.md#method-populateRelation) | Populates the named relation with the related records. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| [`primaryKey()`](#method-primaryKey) static | Returns the primary key name(s) for this AR class. | `ActiveRecord` |
| [`refresh()`](#method-refresh) | Repopulates this active record with the latest data. | `ActiveRecord` |
| <span id="method-rules"></span>[`rules()`](/docs/api/yii/base/model/index.md#method-rules) | Returns the validation rules for attributes. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-safeAttributes"></span>[`safeAttributes()`](/docs/api/yii/base/model/index.md#method-safeAttributes) | Returns the attribute names that are safe to be massively assigned in the current scenario. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-save"></span>[`save()`](/docs/api/yii/db/baseactiverecord/index.md#method-save) | Saves the current record. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-scenarios"></span>[`scenarios()`](/docs/api/yii/base/model/index.md#method-scenarios) | Returns a list of scenarios and the corresponding active attributes. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-setAttribute"></span>[`setAttribute()`](/docs/api/yii/db/baseactiverecord/index.md#method-setAttribute) | Sets the named attribute value. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-setAttributes"></span>[`setAttributes()`](/docs/api/yii/base/model/index.md#method-setAttributes) | Sets the attribute values in a massive way. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-setIsNewRecord"></span>[`setIsNewRecord()`](/docs/api/yii/db/baseactiverecord/index.md#method-setIsNewRecord) | Sets the value indicating whether the record is new. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-setOldAttribute"></span>[`setOldAttribute()`](/docs/api/yii/db/baseactiverecord/index.md#method-setOldAttribute) | Sets the old value of the named attribute. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-setOldAttributes"></span>[`setOldAttributes()`](/docs/api/yii/db/baseactiverecord/index.md#method-setOldAttributes) | Sets the old attribute values. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-setScenario"></span>[`setScenario()`](/docs/api/yii/base/model/index.md#method-setScenario) | Sets the scenario for the model. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| [`tableName()`](#method-tableName) static | Declares the name of the database table associated with this AR class. | `ActiveRecord` |
| <span id="method-toArray"></span>[`toArray()`](/docs/api/yii/base/arrayabletrait/index.md#method-toArray) | Converts the model into an array. | [`yii\base\ArrayableTrait`](/docs/api/yii/base/arrayabletrait/index.md) |
| [`transactions()`](#method-transactions) | Declares which DB operations should be performed within a transaction in different scenarios. | `ActiveRecord` |
| <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-unlink"></span>[`unlink()`](/docs/api/yii/db/baseactiverecord/index.md#method-unlink) | Destroys the relationship between two models. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-unlinkAll"></span>[`unlinkAll()`](/docs/api/yii/db/baseactiverecord/index.md#method-unlinkAll) | Destroys the relationship in current model. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| [`update()`](#method-update) | Saves the changes to this active record into the associated database table. | `ActiveRecord` |
| [`updateAll()`](#method-updateAll) static | Updates the whole table using the provided attribute values and conditions. | `ActiveRecord` |
| [`updateAllCounters()`](#method-updateAllCounters) static | Updates the whole table using the provided counter changes and conditions. | `ActiveRecord` |
| <span id="method-updateAttributes"></span>[`updateAttributes()`](/docs/api/yii/db/baseactiverecord/index.md#method-updateAttributes) | Updates the specified attributes. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-updateCounters"></span>[`updateCounters()`](/docs/api/yii/db/baseactiverecord/index.md#method-updateCounters) | Updates one or several counter columns for the current AR object. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-validate"></span>[`validate()`](/docs/api/yii/base/model/index.md#method-validate) | Performs the data validation. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-validateMultiple"></span>[`validateMultiple()`](/docs/api/yii/base/model/index.md#method-validateMultiple) static | Validates multiple models. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="method-createRelationQuery"></span>[`createRelationQuery()`](/docs/api/yii/db/baseactiverecord/index.md#method-createRelationQuery) protected | Creates a query instance for `has-one` or `has-many` relation. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| [`deleteInternal()`](#method-deleteInternal) protected | Deletes an ActiveRecord without considering transaction. | `ActiveRecord` |
| <span id="method-extractFieldsFor"></span>[`extractFieldsFor()`](/docs/api/yii/base/arrayabletrait/index.md#method-extractFieldsFor) protected | Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id". | [`yii\base\ArrayableTrait`](/docs/api/yii/base/arrayabletrait/index.md) |
| <span id="method-extractRootFields"></span>[`extractRootFields()`](/docs/api/yii/base/arrayabletrait/index.md#method-extractRootFields) protected | Extracts the root field names from nested fields. | [`yii\base\ArrayableTrait`](/docs/api/yii/base/arrayabletrait/index.md) |
| [`insertInternal()`](#method-insertInternal) protected | Inserts an ActiveRecord into DB without considering transaction. | `ActiveRecord` |
| <span id="method-refreshInternal"></span>[`refreshInternal()`](/docs/api/yii/db/baseactiverecord/index.md#method-refreshInternal) protected | Repopulates this active record with the latest data from a newly fetched instance. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="method-resolveFields"></span>[`resolveFields()`](/docs/api/yii/base/arrayabletrait/index.md#method-resolveFields) protected | Determines which fields can be returned by [`toArray()`](/docs/api/yii/base/arrayabletrait/index.md#method-toArray). | [`yii\base\ArrayableTrait`](/docs/api/yii/base/arrayabletrait/index.md) |
| <span id="method-updateInternal"></span>[`updateInternal()`](/docs/api/yii/db/baseactiverecord/index.md#method-updateInternal) protected |  | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |

## Events

| Event | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="event-EVENT_INIT"></span>[`EVENT_INIT`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_INIT) | `yii\db\Event` | An event that is triggered when the record is initialized via [`init()`](/docs/api/yii/db/baseactiverecord/index.md#method-init). Event name: `'init'`. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="event-EVENT_AFTER_FIND"></span>[`EVENT_AFTER_FIND`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_FIND) | `yii\db\Event` | An event that is triggered after the record is created and populated with query result. Event name: `'afterFind'`. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="event-EVENT_BEFORE_INSERT"></span>[`EVENT_BEFORE_INSERT`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_BEFORE_INSERT) | [`yii\base\ModelEvent`](/docs/api/yii/base/modelevent/index.md) | An event that is triggered before inserting a record. Event name: `'beforeInsert'`. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="event-EVENT_AFTER_INSERT"></span>[`EVENT_AFTER_INSERT`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_INSERT) | [`AfterSaveEvent`](/docs/api/yii/db/aftersaveevent/index.md) | An event that is triggered after a record is inserted. Event name: `'afterInsert'`. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="event-EVENT_BEFORE_UPDATE"></span>[`EVENT_BEFORE_UPDATE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_BEFORE_UPDATE) | [`yii\base\ModelEvent`](/docs/api/yii/base/modelevent/index.md) | An event that is triggered before updating a record. Event name: `'beforeUpdate'`. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="event-EVENT_AFTER_UPDATE"></span>[`EVENT_AFTER_UPDATE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_UPDATE) | [`AfterSaveEvent`](/docs/api/yii/db/aftersaveevent/index.md) | An event that is triggered after a record is updated. Event name: `'afterUpdate'`. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="event-EVENT_BEFORE_DELETE"></span>[`EVENT_BEFORE_DELETE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_BEFORE_DELETE) | [`yii\base\ModelEvent`](/docs/api/yii/base/modelevent/index.md) | An event that is triggered before deleting a record. Event name: `'beforeDelete'`. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="event-EVENT_AFTER_DELETE"></span>[`EVENT_AFTER_DELETE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_DELETE) | `yii\db\Event` | An event that is triggered after a record is deleted. Event name: `'afterDelete'`. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="event-EVENT_AFTER_REFRESH"></span>[`EVENT_AFTER_REFRESH`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_REFRESH) | `yii\db\Event` | An event that is triggered after a record is refreshed. Event name: `'afterRefresh'`. Available since 2.0.8. | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) |
| <span id="event-EVENT_BEFORE_VALIDATE"></span>[`EVENT_BEFORE_VALIDATE`](/docs/api/yii/base/model/index.md#event-EVENT_BEFORE_VALIDATE) | [`yii\base\ModelEvent`](/docs/api/yii/base/modelevent/index.md) | An event raised at the beginning of [`validate()`](/docs/api/yii/base/model/index.md#method-validate). Event name: `'beforeValidate'`. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| <span id="event-EVENT_AFTER_VALIDATE"></span>[`EVENT_AFTER_VALIDATE`](/docs/api/yii/base/model/index.md#event-EVENT_AFTER_VALIDATE) | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | An event raised at the end of [`validate()`](/docs/api/yii/base/model/index.md#method-validate) Event name: `'afterValidate'`. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |

## Constants

| Constant | Value | Description | Defined by |
| --- | --- | --- | --- |
| <span id="const-OP_INSERT"></span>`OP_INSERT` | `0x1` | The insert operation. This is mainly used when overriding [`transactions()`](/docs/api/yii/db/activerecord/index.md#method-transactions) to specify which operations are transactional. | `ActiveRecord` |
| <span id="const-OP_UPDATE"></span>`OP_UPDATE` | `0x2` | The update operation. This is mainly used when overriding [`transactions()`](/docs/api/yii/db/activerecord/index.md#method-transactions) to specify which operations are transactional. | `ActiveRecord` |
| <span id="const-OP_DELETE"></span>`OP_DELETE` | `0x4` | The delete operation. This is mainly used when overriding [`transactions()`](/docs/api/yii/db/activerecord/index.md#method-transactions) to specify which operations are transactional. | `ActiveRecord` |
| <span id="const-OP_ALL"></span>`OP_ALL` | `0x7` | All three operations: insert, update, delete. | `ActiveRecord` |
| <span id="const-SCENARIO_DEFAULT"></span>[`SCENARIO_DEFAULT`](/docs/api/yii/base/model/index.md#const-SCENARIO_DEFAULT) | `'default'` | The name of the default scenario. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |

## Method details

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

```php
public function attributes(): array
```

Returns the list of all attribute names of the model.

The default implementation will return all column names of the table associated with this AR class.

**Returns**

`array`: List of attribute names.

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

```php
public function delete(): int|false
```

Deletes the table row corresponding to this active record.

This method performs the following steps in order:

1. call [`beforeDelete()`](/docs/api/yii/db/baseactiverecord/index.md#method-beforeDelete). If the method returns `false`, it will skip the
   rest of the steps;
2. delete the record from the database;
3. call [`afterDelete()`](/docs/api/yii/db/baseactiverecord/index.md#method-afterDelete).

In the above step 1 and 3, events named [`EVENT_BEFORE_DELETE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_BEFORE_DELETE) and [`EVENT_AFTER_DELETE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_DELETE)
will be raised by the corresponding methods.

**Returns**

`int|false`: The number of rows deleted, or `false` if the deletion is unsuccessful for some reason. Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.

**Throws**

- [`StaleObjectException`](/docs/api/yii/db/staleobjectexception/index.md): if [optimistic locking](/docs/api/yii/db/baseactiverecord/index.md#method-optimisticLock) is enabled and the data being deleted is outdated.
- [`Throwable`](https://www.php.net/manual/en/class.throwable.php): in case delete failed.

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

```php
public static function deleteAll(string|array|null $condition = null, array $params = []): int
```

Deletes rows in the table using the provided conditions.

For example, to delete all customers whose status is 3:

```
Customer::deleteAll('status = 3');
```

> Warning: If you do not specify any condition, this method will delete **all** rows in the table.

Note that this method will not trigger any events. If you need [`EVENT_BEFORE_DELETE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_BEFORE_DELETE) or
[`EVENT_AFTER_DELETE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_DELETE) to be triggered, you need to [find](/docs/api/yii/db/activerecord/index.md#method-find) the models first and then
call [`delete()`](/docs/api/yii/db/activerecord/index.md#method-delete) on each of them. For example an equivalent of the example above would be:

```
$models = Customer::find()->where('status = 3')->all();
foreach ($models as $model) {
    $model->delete();
}
```

For a large set of models you might consider using [`ActiveQuery::each()`](/docs/api/yii/db/activequery/index.md#method-each) to keep memory usage within limits.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `string\|array\|null` | The conditions that will be put in the WHERE part of the DELETE SQL. 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**

`int`: The number of rows deleted

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

```php
public function equals(yii\db\ActiveRecord $record): bool
```

Returns a value indicating whether the given active record is the same as the current one.

The comparison is made by comparing the table names and the primary key values of the two active records.
If one of the records [is new](/docs/api/yii/db/baseactiverecord/index.md#property-isNewRecord) they are also considered not equal.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$record` | [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) | Record to compare to |

**Returns**

`bool`: Whether the two active records refer to the same row in the same database table.

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

```php
public static function find(): yii\db\ActiveQuery<static>
```

Creates an [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md) instance for query purpose.

The returned [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md) instance can be further customized by calling
methods defined in [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md) before `one()` or `all()` is called to return
populated ActiveRecord instances. For example,

```
// find the customer whose ID is 1
$customer = Customer::find()->where(['id' => 1])->one();

// find all active customers and order them by their age:
$customers = Customer::find()
    ->where(['status' => 1])
    ->orderBy('age')
    ->all();
```

This method is also called by [`BaseActiveRecord::hasOne()`](/docs/api/yii/db/baseactiverecord/index.md#method-hasOne) and [`BaseActiveRecord::hasMany()`](/docs/api/yii/db/baseactiverecord/index.md#method-hasMany) to
create a relational query.

You may override this method to return a customized query. For example,

```
class Customer extends ActiveRecord
{
    public static function find()
    {
        // use CustomerQuery instead of the default ActiveQuery
        return new CustomerQuery(get_called_class());
    }
}
```

The following code shows how to apply a default condition for all queries:

```
class Customer extends ActiveRecord
{
    public static function find()
    {
        return parent::find()->where(['deleted' => false]);
    }
}

// Use andWhere()/orWhere() to apply the default condition
// SELECT FROM customer WHERE `deleted`=:deleted AND age>30
$customers = Customer::find()->andWhere('age>30')->all();

// Use where() to ignore the default condition
// SELECT FROM customer WHERE age>30
$customers = Customer::find()->where('age>30')->all();
```

**Returns**

[`ActiveQuery`](/docs/api/yii/db/activequery/index.md)`<static>`: The newly created [`ActiveQuery`](/docs/api/yii/db/activequery/index.md) instance.

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

```php
public static function findBySql(string $sql, array $params = []): yii\db\ActiveQuery<static>
```

Creates an [`ActiveQuery`](/docs/api/yii/db/activequery/index.md) instance with a given SQL statement.

Note that because the SQL statement is already specified, calling additional
query modification methods (such as `where()`, `order()`) on the created [`ActiveQuery`](/docs/api/yii/db/activequery/index.md)
instance will have no effect. However, calling `with()`, `asArray()` or `indexBy()` is
still fine.

Below is an example:

```
$customers = Customer::findBySql('SELECT * FROM customer')->all();
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$sql` | `string` | The SQL statement to be executed |
| `$params` | `array` | Parameters to be bound to the SQL statement during execution. |

**Returns**

[`ActiveQuery`](/docs/api/yii/db/activequery/index.md)`<static>`: The newly created [`ActiveQuery`](/docs/api/yii/db/activequery/index.md) instance

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

```php
public static function getDb(): yii\db\Connection
```

Returns the database connection used by this AR class.

By default, the "db" application component is used as the database connection.
You may override this method if you want to use a different database connection.

**Returns**

[`Connection`](/docs/api/yii/db/connection/index.md): The database connection used by this AR class.

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

```php
public static function getTableSchema(yii\db\Connection|null $db = null): yii\db\TableSchema
```

Returns the schema information of the DB table associated with this AR class.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to retrieve the schema. If `null`, the connection returned by [`getDb()`](/docs/api/yii/db/activerecord/index.md#method-getDb) will be used. |

**Returns**

[`TableSchema`](/docs/api/yii/db/tableschema/index.md): The schema information of the DB table associated with this AR class.

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if the table for the AR class does not exist.

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

```php
public function hasMany(class-string<yii\db\T> $class, mixed $link): yii\db\ActiveQuery<yii\db\T>
```

Declares a `has-many` relation.

The declaration is returned in terms of a relational [`ActiveQuery`](/docs/api/yii/db/activequery/index.md) instance
through which the related record can be queried and retrieved back.

A `has-many` relation means that there are multiple related records matching
the criteria set by this relation, e.g., a customer has many orders.

For example, to declare the `orders` relation for `Customer` class, we can write
the following code in the `Customer` class:

```
public function getOrders()
{
    return $this->hasMany(Order::class, ['customer_id' => 'id']);
}
```

Note that in the above, the 'customer_id' key in the `$link` parameter refers to
an attribute name in the related class `Order`, while the 'id' value refers to
an attribute name in the current AR class.

Call methods declared in [`ActiveQuery`](/docs/api/yii/db/activequery/index.md) to further customize the relation.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$class` | `class-string<yii\db\T>` | The class name of the related record. |
| `$link` | `mixed` | The primary-foreign key constraint. The keys of the array refer to the attributes of the record associated with the `$class` model, while the values of the array refer to the corresponding attributes in **this** AR class. |

**Returns**

[`ActiveQuery`](/docs/api/yii/db/activequery/index.md)`<yii\db\T>`: The relational query object.

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

```php
public function hasOne(class-string<yii\db\T> $class, mixed $link): yii\db\ActiveQuery<yii\db\T>
```

Declares a `has-one` relation.

The declaration is returned in terms of a relational [`ActiveQuery`](/docs/api/yii/db/activequery/index.md) instance
through which the related record can be queried and retrieved back.

A `has-one` relation means that there is at most one related record matching
the criteria set by this relation, e.g., a customer has one country.

For example, to declare the `country` relation for `Customer` class, we can write
the following code in the `Customer` class:

```
public function getCountry()
{
    return $this->hasOne(Country::class, ['id' => 'country_id']);
}
```

Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name
in the related class `Country`, while the 'country_id' value refers to an attribute name
in the current AR class.

Call methods declared in [`ActiveQuery`](/docs/api/yii/db/activequery/index.md) to further customize the relation.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$class` | `class-string<yii\db\T>` | The class name of the related record. |
| `$link` | `mixed` | The primary-foreign key constraint. The keys of the array refer to the attributes of the record associated with the `$class` model, while the values of the array refer to the corresponding attributes in **this** AR class. |

**Returns**

[`ActiveQuery`](/docs/api/yii/db/activequery/index.md)`<yii\db\T>`: The relational query object.

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

```php
public function insert(bool $runValidation = true, array|null $attributes = null): bool
```

Inserts a row into the associated database table using the attribute values of this record.

This method performs the following steps in order:

1. call [`beforeValidate()`](/docs/api/yii/base/model/index.md#method-beforeValidate) when `$runValidation` is `true`. If [`beforeValidate()`](/docs/api/yii/base/model/index.md#method-beforeValidate)
   returns `false`, the rest of the steps will be skipped;
2. call [`afterValidate()`](/docs/api/yii/base/model/index.md#method-afterValidate) when `$runValidation` is `true`. If validation
   failed, the rest of the steps will be skipped;
3. call [`beforeSave()`](/docs/api/yii/db/baseactiverecord/index.md#method-beforeSave). If [`beforeSave()`](/docs/api/yii/db/baseactiverecord/index.md#method-beforeSave) returns `false`,
   the rest of the steps will be skipped;
4. insert the record into database. If this fails, it will skip the rest of the steps;
5. call [`afterSave()`](/docs/api/yii/db/baseactiverecord/index.md#method-afterSave);

In the above step 1, 2, 3 and 5, events [`EVENT_BEFORE_VALIDATE`](/docs/api/yii/base/model/index.md#event-EVENT_BEFORE_VALIDATE),
[`EVENT_AFTER_VALIDATE`](/docs/api/yii/base/model/index.md#event-EVENT_AFTER_VALIDATE), [`EVENT_BEFORE_INSERT`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_BEFORE_INSERT), and [`EVENT_AFTER_INSERT`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_INSERT)
will be raised by the corresponding methods.

Only the [changed attribute values](/docs/api/yii/db/baseactiverecord/index.md#property-dirtyAttributes) will be inserted into database.

If the table's primary key is auto-incremental and is `null` during insertion,
it will be populated with the actual value after insertion.

For example, to insert a customer record:

```
$customer = new Customer;
$customer->name = $name;
$customer->email = $email;
$customer->insert();
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$runValidation` | `bool` | Whether to perform validation (calling [`validate()`](/docs/api/yii/base/model/index.md#method-validate)) before saving the record. Defaults to `true`. If the validation fails, the record will not be saved to the database and this method will return `false`. |
| `$attributes` | `array\|null` | List of attributes that need to be saved. Defaults to `null`, meaning all attributes that are loaded from DB will be saved. |

**Returns**

`bool`: Whether the attributes are valid and the record is inserted successfully.

**Throws**

- [`Throwable`](https://www.php.net/manual/en/class.throwable.php): in case insert failed.

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

```php
public function isTransactional(int $operation): bool
```

Returns a value indicating whether the specified operation is transactional in the current [`$scenario`](/docs/api/yii/base/model/index.md#property-scenario).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$operation` | `int` | The operation to check. Possible values are [`OP_INSERT`](/docs/api/yii/db/activerecord/index.md#const-OP_INSERT), [`OP_UPDATE`](/docs/api/yii/db/activerecord/index.md#const-OP_UPDATE) and [`OP_DELETE`](/docs/api/yii/db/activerecord/index.md#const-OP_DELETE). |

**Returns**

`bool`: Whether the specified operation is transactional in the current [`$scenario`](/docs/api/yii/base/model/index.md#property-scenario).

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

```php
public function loadDefaultValues(bool $skipIfSet = true): $this
```

Loads default values from database table schema.

You may call this method to load default values after creating a new instance:

```
// class Customer extends \yii\db\ActiveRecord
$customer = new Customer();
$customer->loadDefaultValues();
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$skipIfSet` | `bool` | Whether existing value should be preserved. This will only set defaults for attributes that are `null`. |

**Returns**

`$this`: The model instance itself.

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

```php
public static function populateRecord(mixed $record, mixed $row, yii\db\Connection|null $db = null): mixed
```

Populates an active record object using a row of data from the database/storage.

This is an internal method meant to be called to create active record objects after
fetching data from the database. It is mainly used by [`ActiveQuery`](/docs/api/yii/db/activequery/index.md) to populate
the query results into active records.

When calling this method manually you should call [`afterFind()`](/docs/api/yii/db/baseactiverecord/index.md#method-afterFind) on the created
record to trigger the [afterFind Event](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_FIND).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$record` | `mixed` | The record to be populated. In most cases this will be an instance created by [`instantiate()`](/docs/api/yii/db/baseactiverecord/index.md#method-instantiate) beforehand. |
| `$row` | `mixed` | Attribute values (name => value) |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to retrieve the row and its schema. |

**Returns**

`mixed`

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

```php
public static function primaryKey(): string[]
```

Returns the primary key name(s) for this AR class.

The default implementation will return the primary key(s) as declared
in the DB table that is associated with this AR class.

If the DB table does not declare any primary key, you should override
this method to return the attributes that you want to use as primary keys
for this AR class.

Note that an array should be returned even for a table with single primary key.

**Returns**

`string[]`: The primary keys of the associated database table.

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

```php
public function refresh(): bool
```

Repopulates this active record with the latest data.

If the refresh is successful, an [`EVENT_AFTER_REFRESH`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_REFRESH) event will be triggered.
This event is available since version 2.0.8.

**Returns**

`bool`: Whether the row still exists in the database. If `true`, the latest data will be populated to this active record. Otherwise, this record will remain unchanged.

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

```php
public static function tableName(): string
```

Declares the name of the database table associated with this AR class.

By default this method returns the class name as the table name by calling [`Inflector::camel2id()`](/docs/api/yii/helpers/baseinflector/index.md#method-camel2id)
with prefix [`Connection::$tablePrefix`](/docs/api/yii/db/connection/index.md#property-tablePrefix). For example if [`Connection::$tablePrefix`](/docs/api/yii/db/connection/index.md#property-tablePrefix) is `tbl_`,
`Customer` becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method
if the table is not named after this convention.

**Returns**

`string`: The table name

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

```php
public function transactions(): array
```

Declares which DB operations should be performed within a transaction in different scenarios.

The supported DB operations are: [`OP_INSERT`](/docs/api/yii/db/activerecord/index.md#const-OP_INSERT), [`OP_UPDATE`](/docs/api/yii/db/activerecord/index.md#const-OP_UPDATE) and [`OP_DELETE`](/docs/api/yii/db/activerecord/index.md#const-OP_DELETE),
which correspond to the [`insert()`](/docs/api/yii/db/activerecord/index.md#method-insert), [`update()`](/docs/api/yii/db/activerecord/index.md#method-update) and [`delete()`](/docs/api/yii/db/activerecord/index.md#method-delete) methods, respectively.
By default, these methods are NOT enclosed in a DB transaction.

In some scenarios, to ensure data consistency, you may want to enclose some or all of them
in transactions. You can do so by overriding this method and returning the operations
that need to be transactional. For example,

```
return [
    'admin' => self::OP_INSERT,
    'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
    // the above is equivalent to the following:
    // 'api' => self::OP_ALL,

];
```

The above declaration specifies that in the "admin" scenario, the insert operation ([`insert()`](/docs/api/yii/db/activerecord/index.md#method-insert))
should be done in a transaction; and in the "api" scenario, all the operations should be done
in a transaction.

**Returns**

`array`: The declarations of transactional operations. The array keys are scenarios names, and the array values are the corresponding transaction operations.

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

```php
public function update(bool $runValidation = true, array|null $attributeNames = null): int|false
```

Saves the changes to this active record into the associated database table.

This method performs the following steps in order:

1. call [`beforeValidate()`](/docs/api/yii/base/model/index.md#method-beforeValidate) when `$runValidation` is `true`. If [`beforeValidate()`](/docs/api/yii/base/model/index.md#method-beforeValidate)
   returns `false`, the rest of the steps will be skipped;
2. call [`afterValidate()`](/docs/api/yii/base/model/index.md#method-afterValidate) when `$runValidation` is `true`. If validation
   failed, the rest of the steps will be skipped;
3. call [`beforeSave()`](/docs/api/yii/db/baseactiverecord/index.md#method-beforeSave). If [`beforeSave()`](/docs/api/yii/db/baseactiverecord/index.md#method-beforeSave) returns `false`,
   the rest of the steps will be skipped;
4. save the record into database. If this fails, it will skip the rest of the steps;
5. call [`afterSave()`](/docs/api/yii/db/baseactiverecord/index.md#method-afterSave);

In the above step 1, 2, 3 and 5, events [`EVENT_BEFORE_VALIDATE`](/docs/api/yii/base/model/index.md#event-EVENT_BEFORE_VALIDATE),
[`EVENT_AFTER_VALIDATE`](/docs/api/yii/base/model/index.md#event-EVENT_AFTER_VALIDATE), [`EVENT_BEFORE_UPDATE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_BEFORE_UPDATE), and [`EVENT_AFTER_UPDATE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_UPDATE)
will be raised by the corresponding methods.

Only the [changed attribute values](/docs/api/yii/db/baseactiverecord/index.md#property-dirtyAttributes) will be saved into database.

For example, to update a customer record:

```
$customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->update();
```

Note that it is possible the update does not affect any row in the table.
In this case, this method will return 0. For this reason, you should use the following
code to check if update() is successful or not:

```
if ($customer->update() !== false) {
    // update successful
} else {
    // update failed
}
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$runValidation` | `bool` | Whether to perform validation (calling [`validate()`](/docs/api/yii/base/model/index.md#method-validate)) before saving the record. Defaults to `true`. If the validation fails, the record will not be saved to the database and this method will return `false`. |
| `$attributeNames` | `array\|null` | List of attributes that need to be saved. Defaults to `null`, meaning all attributes that are loaded from DB will be saved. |

**Returns**

`int|false`: The number of rows affected, or false if validation fails or [`beforeSave()`](/docs/api/yii/db/baseactiverecord/index.md#method-beforeSave) stops the updating process.

**Throws**

- [`StaleObjectException`](/docs/api/yii/db/staleobjectexception/index.md): if [optimistic locking](/docs/api/yii/db/baseactiverecord/index.md#method-optimisticLock) is enabled and the data being updated is outdated.
- [`Throwable`](https://www.php.net/manual/en/class.throwable.php): in case update failed.

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

```php
public static function updateAll(array $attributes, string|array $condition = '', array $params = []): int
```

Updates the whole table using the provided attribute values and conditions.

For example, to change the status to be 1 for all customers whose status is 2:

```
Customer::updateAll(['status' => 1], 'status = 2');
```

> Warning: If you do not specify any condition, this method will update **all** rows in the table.

Note that this method will not trigger any events. If you need [`EVENT_BEFORE_UPDATE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_BEFORE_UPDATE) or
[`EVENT_AFTER_UPDATE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_UPDATE) to be triggered, you need to [find](/docs/api/yii/db/activerecord/index.md#method-find) the models first and then
call [`update()`](/docs/api/yii/db/activerecord/index.md#method-update) on each of them. For example an equivalent of the example above would be:

```
$models = Customer::find()->where('status = 2')->all();
foreach ($models as $model) {
    $model->status = 1;
    $model->update(false); // skipping validation as no user input is involved
}
```

For a large set of models you might consider using [`ActiveQuery::each()`](/docs/api/yii/db/activequery/index.md#method-each) to keep memory usage within limits.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attributes` | `array` | Attribute values (name-value pairs) to be saved into the table |
| `$condition` | `string\|array` | The conditions that will be put in the WHERE part of the UPDATE SQL. 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**

`int`: The number of rows updated

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

```php
public static function updateAllCounters(array $counters, string|array $condition = '', array $params = []): int
```

Updates the whole table using the provided counter changes and conditions.

For example, to increment all customers' age by 1,

```
Customer::updateAllCounters(['age' => 1]);
```

Note that this method will not trigger any events.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$counters` | `array` | The counters to be updated (attribute name => increment value). Use negative values if you want to decrement the counters. |
| `$condition` | `string\|array` | The conditions that will be put in the WHERE part of the UPDATE SQL. 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. Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method. |

**Returns**

`int`: The number of rows updated

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

```php
protected function deleteInternal(): int|false
```

Deletes an ActiveRecord without considering transaction.

**Returns**

`int|false`: The number of rows deleted, or `false` if the deletion is unsuccessful for some reason. Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.

**Throws**

- [`StaleObjectException`](/docs/api/yii/db/staleobjectexception/index.md)

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

```php
protected function insertInternal(array|null $attributes = null): bool
```

Inserts an ActiveRecord into DB without considering transaction.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attributes` | `array\|null` | List of attributes that need to be saved. Defaults to `null`, meaning all attributes that are loaded from DB will be saved. |

**Returns**

`bool`: Whether the record is inserted successfully.