# BaseActiveRecord

> 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) › BaseActiveRecord

| abstract class | `yii\db\BaseActiveRecord` |
| --- | --- |
| Extends | [`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 | [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md), [`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) |
| 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/BaseActiveRecord.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/db/BaseActiveRecord.php#L43) |

1 subclass:

- [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md)

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

See [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) for a concrete implementation.

## 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` read-only | `array` | The changed attribute values (name-value pairs). | `BaseActiveRecord` |
| <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` | `bool` | Whether the record is new and should be inserted when calling [`save()`](/docs/api/yii/db/baseactiverecord/index.md#method-save). | `BaseActiveRecord` |
| <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) |
| [`$oldAttributes`](#property-oldAttributes) | `array\|null` | Old attribute values to be set. | `BaseActiveRecord` |
| [`$oldPrimaryKey`](#property-oldPrimaryKey) read-only | `mixed` | The old primary key value. | `BaseActiveRecord` |
| [`$primaryKey`](#property-primaryKey) read-only | `mixed` | The primary key value. | `BaseActiveRecord` |
| <span id="property-relatedRecords"></span>`$relatedRecords` read-only | `array` | An array of related records indexed by relation names. | `BaseActiveRecord` |
| <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) |
| [`__get()`](#method-__get) | PHP getter magic method. | `BaseActiveRecord` |
| [`__isset()`](#method-__isset) | Checks if a property value is null. | `BaseActiveRecord` |
| [`__set()`](#method-__set) | PHP setter magic method. | `BaseActiveRecord` |
| [`__unset()`](#method-__unset) | Sets a component property to be null. | `BaseActiveRecord` |
| <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) |
| [`afterDelete()`](#method-afterDelete) | This method is invoked after deleting a record. | `BaseActiveRecord` |
| [`afterFind()`](#method-afterFind) | This method is called when the AR object is created and populated with the query result. | `BaseActiveRecord` |
| [`afterRefresh()`](#method-afterRefresh) | This method is called when the AR object is refreshed. | `BaseActiveRecord` |
| [`afterSave()`](#method-afterSave) | This method is called at the end of inserting or updating a record. | `BaseActiveRecord` |
| <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) |
| <span id="method-attributes"></span>[`attributes()`](/docs/api/yii/base/model/index.md#method-attributes) | Returns the list of attribute names. | [`yii\base\Model`](/docs/api/yii/base/model/index.md) |
| [`beforeDelete()`](#method-beforeDelete) | This method is invoked before deleting a record. | `BaseActiveRecord` |
| [`beforeSave()`](#method-beforeSave) | This method is called at the beginning of inserting or updating a record. | `BaseActiveRecord` |
| <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) |
| [`canGetProperty()`](#method-canGetProperty) | Returns a value indicating whether a property can be read. | `BaseActiveRecord` |
| [`canSetOldAttribute()`](#method-canSetOldAttribute) | Returns if the old named attribute can be set. | `BaseActiveRecord` |
| [`canSetProperty()`](#method-canSetProperty) | Returns a value indicating whether a property can be set. | `BaseActiveRecord` |
| <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. | `BaseActiveRecord` |
| [`deleteAll()`](#method-deleteAll) static | Deletes rows in the table using the provided conditions. | `BaseActiveRecord` |
| <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. | `BaseActiveRecord` |
| [`extraFields()`](#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` |
| [`fields()`](#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` |
| <span id="method-find"></span>[`find()`](/docs/api/yii/db/activerecordinterface/index.md#method-find) static abstract | Creates an [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md) instance for query purpose. | [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md) |
| [`findAll()`](#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` |
| [`findOne()`](#method-findOne) static | Returns a single active record model instance by a primary key or an array of column values. | `BaseActiveRecord` |
| <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) |
| [`getAttribute()`](#method-getAttribute) | Returns the named attribute value. | `BaseActiveRecord` |
| [`getAttributeHint()`](#method-getAttributeHint) | Returns the text hint for the specified attribute. | `BaseActiveRecord` |
| [`getAttributeLabel()`](#method-getAttributeLabel) | Returns the text label for the specified attribute. | `BaseActiveRecord` |
| <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) |
| <span id="method-getDb"></span>[`getDb()`](/docs/api/yii/db/activerecordinterface/index.md#method-getDb) static abstract | Returns the connection used by this AR class. | [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md) |
| [`getDirtyAttributes()`](#method-getDirtyAttributes) | Returns the attribute values that have been modified since they are loaded or saved most recently. | `BaseActiveRecord` |
| <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) |
| [`getIsNewRecord()`](#method-getIsNewRecord) | Returns a value indicating whether the current record is new. | `BaseActiveRecord` |
| <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) |
| [`getOldAttribute()`](#method-getOldAttribute) | Returns the old value of the named attribute. | `BaseActiveRecord` |
| [`getOldAttributes()`](#method-getOldAttributes) | Returns the old attribute values. | `BaseActiveRecord` |
| [`getOldPrimaryKey()`](#method-getOldPrimaryKey) | Returns the old primary key value(s). | `BaseActiveRecord` |
| [`getPrimaryKey()`](#method-getPrimaryKey) | Returns the primary key value(s). | `BaseActiveRecord` |
| [`getRelatedRecords()`](#method-getRelatedRecords) | Returns all populated related records. | `BaseActiveRecord` |
| [`getRelation()`](#method-getRelation) | Returns the relation object with the specified name. | `BaseActiveRecord` |
| <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) |
| <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) |
| [`hasAttribute()`](#method-hasAttribute) | Returns a value indicating whether the model has an attribute with the specified name. | `BaseActiveRecord` |
| <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. | `BaseActiveRecord` |
| <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. | `BaseActiveRecord` |
| <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) |
| [`init()`](#method-init) | Initializes the object. | `BaseActiveRecord` |
| <span id="method-insert"></span>[`insert()`](/docs/api/yii/db/activerecordinterface/index.md#method-insert) abstract | Inserts the record into the database using the attribute values of this record. | [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md) |
| <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) |
| [`instantiate()`](#method-instantiate) static | Creates an active record instance. | `BaseActiveRecord` |
| <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) |
| [`isAttributeChanged()`](#method-isAttributeChanged) | Returns a value indicating whether the named attribute has been changed. | `BaseActiveRecord` |
| <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) |
| [`isPrimaryKey()`](#method-isPrimaryKey) static | Returns a value indicating whether the given set of attributes represents the primary key for this model. | `BaseActiveRecord` |
| [`isRelationPopulated()`](#method-isRelationPopulated) | Check whether the named relation has been populated with records. | `BaseActiveRecord` |
| [`link()`](#method-link) | Establishes the relationship between two models. | `BaseActiveRecord` |
| <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) |
| <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) |
| [`loadRelations()`](#method-loadRelations) | Eager loads related models for the already loaded primary model. | `BaseActiveRecord` |
| [`loadRelationsFor()`](#method-loadRelationsFor) static | Eager loads related models for the already loaded primary models. | `BaseActiveRecord` |
| [`markAttributeDirty()`](#method-markAttributeDirty) | Marks an attribute dirty. | `BaseActiveRecord` |
| <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) |
| [`offsetExists()`](#method-offsetExists) | Returns whether there is an element at the specified offset. | `BaseActiveRecord` |
| <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) |
| [`offsetUnset()`](#method-offsetUnset) | Sets the element value at the specified offset to null. | `BaseActiveRecord` |
| <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) |
| [`optimisticLock()`](#method-optimisticLock) | Returns the name of the column that stores the lock version for implementing optimistic locking. | `BaseActiveRecord` |
| [`populateRecord()`](#method-populateRecord) static | Populates an active record object using a row of data from the database/storage. | `BaseActiveRecord` |
| [`populateRelation()`](#method-populateRelation) | Populates the named relation with the related records. | `BaseActiveRecord` |
| <span id="method-primaryKey"></span>[`primaryKey()`](/docs/api/yii/db/activerecordinterface/index.md#method-primaryKey) static abstract | Returns the primary key **name(s)** for this AR class. | [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md) |
| [`refresh()`](#method-refresh) | Repopulates this active record with the latest data. | `BaseActiveRecord` |
| <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) |
| [`save()`](#method-save) | Saves the current record. | `BaseActiveRecord` |
| <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) |
| [`setAttribute()`](#method-setAttribute) | Sets the named attribute value. | `BaseActiveRecord` |
| <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) |
| [`setIsNewRecord()`](#method-setIsNewRecord) | Sets the value indicating whether the record is new. | `BaseActiveRecord` |
| [`setOldAttribute()`](#method-setOldAttribute) | Sets the old value of the named attribute. | `BaseActiveRecord` |
| [`setOldAttributes()`](#method-setOldAttributes) | Sets the old attribute values. | `BaseActiveRecord` |
| <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) |
| <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) |
| <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) |
| [`unlink()`](#method-unlink) | Destroys the relationship between two models. | `BaseActiveRecord` |
| [`unlinkAll()`](#method-unlinkAll) | Destroys the relationship in current model. | `BaseActiveRecord` |
| [`update()`](#method-update) | Saves the changes to this active record into the associated database table. | `BaseActiveRecord` |
| [`updateAll()`](#method-updateAll) static | Updates the whole table using the provided attribute values and conditions. | `BaseActiveRecord` |
| [`updateAllCounters()`](#method-updateAllCounters) static | Updates the whole table using the provided counter changes and conditions. | `BaseActiveRecord` |
| [`updateAttributes()`](#method-updateAttributes) | Updates the specified attributes. | `BaseActiveRecord` |
| [`updateCounters()`](#method-updateCounters) | Updates one or several counter columns for the current AR object. | `BaseActiveRecord` |
| <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) |
| [`createRelationQuery()`](#method-createRelationQuery) protected | Creates a query instance for `has-one` or `has-many` relation. | `BaseActiveRecord` |
| <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) |
| [`refreshInternal()`](#method-refreshInternal) protected | Repopulates this active record with the latest data from a newly fetched instance. | `BaseActiveRecord` |
| <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) |
| [`updateInternal()`](#method-updateInternal) protected |  | `BaseActiveRecord` |

## Events

| Event | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="event-EVENT_INIT"></span>`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` |
| <span id="event-EVENT_AFTER_FIND"></span>`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` |
| <span id="event-EVENT_BEFORE_INSERT"></span>`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` |
| <span id="event-EVENT_AFTER_INSERT"></span>`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` |
| <span id="event-EVENT_BEFORE_UPDATE"></span>`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` |
| <span id="event-EVENT_AFTER_UPDATE"></span>`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` |
| <span id="event-EVENT_BEFORE_DELETE"></span>`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` |
| <span id="event-EVENT_AFTER_DELETE"></span>`EVENT_AFTER_DELETE` | `yii\db\Event` | An event that is triggered after a record is deleted. Event name: `'afterDelete'`. | `BaseActiveRecord` |
| <span id="event-EVENT_AFTER_REFRESH"></span>`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` |
| <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-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) |

## Property details

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

```php
public array|null $oldAttributes
```

Old attribute values to be set.

If set to `null` this record is
considered to be [new](/docs/api/yii/db/baseactiverecord/index.md#property-isNewRecord).

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

```php
public mixed $oldPrimaryKey
```

The old primary key value.

An array (column name => column value) is
returned if the primary key is composite or `$asArray` is `true`. A string is returned otherwise (null will be
returned if the key value is null).

**Access**

Read-only (virtual property).

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

```php
public mixed $primaryKey
```

The primary key value.

An array (column name => column value) is returned
if the primary key is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned
if the key value is null).

**Access**

Read-only (virtual property).

## Method details

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

```php
public function __get(string $name): mixed
```

PHP getter magic method.

This method is overridden so that attributes and related objects can be accessed like properties.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | Property name |

**Returns**

`mixed`: Property value

**Throws**

- [`yii\base\InvalidArgumentException`](/docs/api/yii/base/invalidargumentexception/index.md): if relation name is wrong

**See also**

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

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

```php
public function __isset(string $name): bool
```

Checks if a property value is null.

This method overrides the parent implementation by checking if the named attribute is `null` or not.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The property name or the event name |

**Returns**

`bool`: Whether the property value is null

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

```php
public function __set(string $name, mixed $value): mixed
```

PHP setter magic method.

This method is overridden so that AR attributes can be accessed like properties.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | Property name |
| `$value` | `mixed` | Property value |

**Returns**

`mixed`

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

```php
public function __unset(string $name): mixed
```

Sets a component property to be null.

This method overrides the parent implementation by clearing
the specified attribute value.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The property name or the event name |

**Returns**

`mixed`

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

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

This method is invoked after deleting a record.

The default implementation raises the [`EVENT_AFTER_DELETE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_DELETE) event.
You may override this method to do postprocessing after the record is deleted.
Make sure you call the parent implementation so that the event is raised properly.

**Returns**

`mixed`

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

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

This method is called when the AR object is created and populated with the query result.

The default implementation will trigger an [`EVENT_AFTER_FIND`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_FIND) event.
When overriding this method, make sure you call the parent implementation to ensure the
event is triggered.

**Returns**

`mixed`

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

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

This method is called when the AR object is refreshed.

The default implementation will trigger an [`EVENT_AFTER_REFRESH`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_REFRESH) event.
When overriding this method, make sure you call the parent implementation to ensure the
event is triggered.

**Returns**

`mixed`

**Since**

2.0.8

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

```php
public function afterSave(bool $insert, array $changedAttributes): mixed
```

This method is called at the end of inserting or updating a record.

The default implementation will trigger an [`EVENT_AFTER_INSERT`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_INSERT) event when `$insert` is `true`,
or an [`EVENT_AFTER_UPDATE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_AFTER_UPDATE) event if `$insert` is `false`. The event class used is [`AfterSaveEvent`](/docs/api/yii/db/aftersaveevent/index.md).
When overriding this method, make sure you call the parent implementation so that
the event is triggered.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$insert` | `bool` | Whether this method called while inserting a record. If `false`, it means the method is called while updating a record. |
| `$changedAttributes` | `array` | The old values of attributes that had changed and were saved. You can use this parameter to take action based on the changes made for example send an email when the password had changed or implement audit trail that tracks all the changes. `$changedAttributes` gives you the old attribute values while the active record (`$this`) has already the new, updated values. Note that no automatic type conversion performed by default. You may use [`AttributeTypecastBehavior`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md) to facilitate attribute typecasting. See https://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting. |

**Returns**

`mixed`

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

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

This method is invoked before deleting a record.

The default implementation raises the [`EVENT_BEFORE_DELETE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_BEFORE_DELETE) event.
When overriding this method, make sure you call the parent implementation like the following:

```
public function beforeDelete()
{
    if (!parent::beforeDelete()) {
        return false;
    }

    // ...custom code here...
    return true;
}
```

**Returns**

`bool`: Whether the record should be deleted. Defaults to `true`.

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

```php
public function beforeSave(bool $insert): bool
```

This method is called at the beginning of inserting or updating a record.

The default implementation will trigger an [`EVENT_BEFORE_INSERT`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_BEFORE_INSERT) event when `$insert` is `true`,
or an [`EVENT_BEFORE_UPDATE`](/docs/api/yii/db/baseactiverecord/index.md#event-EVENT_BEFORE_UPDATE) event if `$insert` is `false`.
When overriding this method, make sure you call the parent implementation like the following:

```
public function beforeSave($insert)
{
    if (!parent::beforeSave($insert)) {
        return false;
    }

    // ...custom code here...
    return true;
}
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$insert` | `bool` | Whether this method called while inserting a record. If `false`, it means the method is called while updating a record. |

**Returns**

`bool`: Whether the insertion or updating should continue. If `false`, the insertion or updating will be cancelled.

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

```php
public function canGetProperty(mixed $name, mixed $checkVars = true, mixed $checkBehaviors = true): bool
```

Returns a value indicating whether a property can be read.

A property can be read if:

- the class has a getter method associated with the specified name
  (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when `$checkVars` is true);
- an attached behavior has a readable property of the given name (when `$checkBehaviors` is true).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `mixed` | The property name |
| `$checkVars` | `mixed` | Whether to treat member variables as properties |
| `$checkBehaviors` | `mixed` | Whether to treat behaviors' properties as properties of this component |

**Returns**

`bool`: Whether the property can be read

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

```php
public function canSetOldAttribute(string $name): bool
```

Returns if the old named attribute can be set.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The attribute name |

**Returns**

`bool`: Whether the old attribute can be set

**See also**

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

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

```php
public function canSetProperty(mixed $name, mixed $checkVars = true, mixed $checkBehaviors = true): bool
```

Returns a value indicating whether a property can be set.

A property can be written if:

- the class has a setter method associated with the specified name
  (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when `$checkVars` is true);
- an attached behavior has a writable property of the given name (when `$checkBehaviors` is true).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `mixed` | The property name |
| `$checkVars` | `mixed` | Whether to treat member variables as properties |
| `$checkBehaviors` | `mixed` | Whether to treat behaviors' properties as properties of this component |

**Returns**

`bool`: Whether the property can be written

### 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.
- [`Exception`](/docs/api/yii/db/exception/index.md): in case delete failed.

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

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

Deletes rows in the table using the provided conditions.

WARNING: If you do not specify any condition, this method will delete ALL rows in the table.

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

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

**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. |

**Returns**

`int`: The number of rows deleted

**Throws**

- [`yii\base\NotSupportedException`](/docs/api/yii/base/notsupportedexception/index.md): if not overridden.

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

```php
public function equals(yii\db\ActiveRecordInterface $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` | [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md) | Record to compare to |

**Returns**

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

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

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

Returns the list of fields that can be expanded further and returned by [`toArray()`](/docs/api/yii/base/arrayabletrait/index.md#method-toArray).

The default implementation returns the names of the relations that have been populated into this record.

This method is similar to [`fields()`](/docs/api/yii/db/baseactiverecord/index.md#method-fields) except that the list of fields returned
by this method are not returned by default by [`toArray()`](/docs/api/yii/base/arrayabletrait/index.md#method-toArray). Only when field names
to be expanded are explicitly specified when calling [`toArray()`](/docs/api/yii/base/arrayabletrait/index.md#method-toArray), will their values
be exported.

The default implementation returns an empty array.

You may override this method to return a list of expandable fields based on some context information
(e.g. the current application user).

**Returns**

`array`: The list of expandable field names or field definitions. Please refer to [`fields()`](/docs/api/yii/db/baseactiverecord/index.md#method-fields) on the format of the return value.

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

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

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.

The default implementation returns the names of the columns whose values have been populated into this record.

A field is a named element in the returned array by [`toArray()`](/docs/api/yii/base/arrayabletrait/index.md#method-toArray).

This method should return an array of field names or field definitions.
If the former, the field name will be treated as an object property name whose value will be used
as the field value. If the latter, the array key should be the field name while the array value should be
the corresponding field definition which can be either an object property name or a PHP callable
returning the corresponding field value. The signature of the callable should be:

```
function ($model, $field) {
    // return field value
}
```

For example, the following code declares four fields:

- `email`: the field name is the same as the property name `email`;
- `firstName` and `lastName`: the field names are `firstName` and `lastName`, and their
  values are obtained from the `first_name` and `last_name` properties;
- `fullName`: the field name is `fullName`. Its value is obtained by concatenating `first_name`
  and `last_name`.

```
return [
    'email',
    'firstName' => 'first_name',
    'lastName' => 'last_name',
    'fullName' => function ($model) {
        return $model->first_name . ' ' . $model->last_name;
    },
];
```

In this method, you may also want to return different lists of fields based on some context
information. For example, depending on [`$scenario`](/docs/api/yii/base/model/index.md#property-scenario) or the privilege of the current application user,
you may return different sets of visible fields or filter out some fields.

The default implementation of this method returns [`attributes()`](/docs/api/yii/base/model/index.md#method-attributes) indexed by the same attribute names.

**Returns**

`array`: The list of field names or field definitions.

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

```php
public static function findAll(mixed $condition): static[]
```

Returns a list of active record models that match the specified primary key value(s) or a set of column values.

The method accepts:

 - a scalar value (integer or string): query by a single primary key value and return an array containing the
   corresponding record (or an empty array if not found).
 - a non-associative array: query by a list of primary key values and return the
   corresponding records (or an empty array if none was found).
   Note that an empty condition will result in an empty result as it will be interpreted as a search for
   primary keys and not an empty `WHERE` condition.
 - an associative array of name-value pairs: query by a set of attribute values and return an array of records
   matching all of them (or an empty array if none was found). Note that `['id' => 1, 2]` is treated as
   a non-associative array.
   Column names are limited to current records table columns for SQL DBMS, or filtered otherwise to be limted to simple filter conditions.
 - a yii\db\Expression: The expression will be used directly. (@since 2.0.37)

This method will automatically call the `all()` method and return an array of [ActiveRecord](/docs/api/yii/db/activerecordinterface/index.md)
instances.

> Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work.
> If you need to specify more complex conditions, use [`find()`](/docs/api/yii/db/activerecordinterface/index.md#method-find) in combination with [where()](/docs/api/yii/db/query/index.md#method-where) instead.

See the following code for usage examples:

```
// find the customers whose primary key value is 10
$customers = Customer::findAll(10);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => 10])->all();

// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findAll([10, 11, 12]);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();

// find customers whose age is 30 and whose status is 1
$customers = Customer::findAll(['age' => 30, 'status' => 1]);

// the above code is equivalent to:
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();
```

If you need to pass user input to this method, make sure the input value is scalar or in case of
array condition, make sure the array structure can not be changed from the outside:

```
// yii\web\Controller ensures that $id is scalar
public function actionView($id)
{
    $model = Post::findOne($id);
    // ...
}

// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);

// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
$model = Post::findOne(Yii::$app->request->get('id'));
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `mixed` | Primary key value or a set of column values |

**Returns**

`static[]`: An array of ActiveRecord instances, or an empty array if nothing matches.

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

```php
public static function findOne(mixed $condition): static|null
```

Returns a single active record model instance by a primary key or an array of column values.

The method accepts:

 - a scalar value (integer or string): query by a single primary key value and return the
   corresponding record (or `null` if not found).
 - a non-associative array: query by a list of primary key values and return the
   first record (or `null` if not found).
 - an associative array of name-value pairs: query by a set of attribute values and return a single record
   matching all of them (or `null` if not found). Note that `['id' => 1, 2]` is treated as a non-associative array.
   Column names are limited to current records table columns for SQL DBMS, or filtered otherwise to be limited to simple filter conditions.
 - a yii\db\Expression: The expression will be used directly. (@since 2.0.37)

That this method will automatically call the `one()` method and return an [ActiveRecord](/docs/api/yii/db/activerecordinterface/index.md)
instance.

> Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work.
> If you need to specify more complex conditions, use [`find()`](/docs/api/yii/db/activerecordinterface/index.md#method-find) in combination with [where()](/docs/api/yii/db/query/index.md#method-where) instead.

See the following code for usage examples:

```
// find a single customer whose primary key value is 10
$customer = Customer::findOne(10);

// the above code is equivalent to:
$customer = Customer::find()->where(['id' => 10])->one();

// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findOne([10, 11, 12]);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->one();

// find the first customer whose age is 30 and whose status is 1
$customer = Customer::findOne(['age' => 30, 'status' => 1]);

// the above code is equivalent to:
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
```

If you need to pass user input to this method, make sure the input value is scalar or in case of
array condition, make sure the array structure can not be changed from the outside:

```
// yii\web\Controller ensures that $id is scalar
public function actionView($id)
{
    $model = Post::findOne($id);
    // ...
}

// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);

// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
$model = Post::findOne(Yii::$app->request->get('id'));
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `mixed` | Primary key value or a set of column values |

**Returns**

`static|null`: ActiveRecord instance matching the condition, or `null` if nothing matches.

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

```php
public function getAttribute(string $name): mixed
```

Returns the named attribute value.

If this record is the result of a query and the attribute is not loaded,
`null` will be returned.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The attribute name |

**Returns**

`mixed`: The attribute value. `null` if the attribute is not set or does not exist.

**See also**

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

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

```php
public function getAttributeHint(string $attribute): string
```

Returns the text hint for the specified attribute.

If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attribute` | `string` | The attribute name |

**Returns**

`string`: The attribute hint

**Since**

2.0.4

**See also**

- [`attributeHints()`](/docs/api/yii/base/model/index.md#method-attributeHints)

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

```php
public function getAttributeLabel(string $attribute): string
```

Returns the text label for the specified attribute.

The attribute may be specified in a dot format to retrieve the label from related model or allow this model to override the label defined in related model.
For example, if the attribute is specified as 'relatedModel1.relatedModel2.attr' the function will return the first label definition it can find
in the following order:
- the label for 'relatedModel1.relatedModel2.attr' defined in [`attributeLabels()`](/docs/api/yii/base/model/index.md#method-attributeLabels) of this model;
- the label for 'relatedModel2.attr' defined in related model represented by relation 'relatedModel1' of this model;
- the label for 'attr' defined in related model represented by relation 'relatedModel2' of relation 'relatedModel1'.
  If no label definition was found then the value of $this->generateAttributeLabel('relatedModel1.relatedModel2.attr') will be returned.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attribute` | `string` | The attribute name |

**Returns**

`string`: The attribute label

**See also**

- [`attributeLabels()`](/docs/api/yii/base/model/index.md#method-attributeLabels)
- [`generateAttributeLabel()`](/docs/api/yii/base/model/index.md#method-generateAttributeLabel)

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

```php
public function getDirtyAttributes(string[]|null $names = null): array
```

Returns the attribute values that have been modified since they are loaded or saved most recently.

The comparison of new and old values is made for identical values using `===`.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$names` | `string[]\|null` | The names of the attributes whose values may be returned if they are changed recently. If null, [`attributes()`](/docs/api/yii/base/model/index.md#method-attributes) will be used. |

**Returns**

`array`: The changed attribute values (name-value pairs)

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

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

Returns a value indicating whether the current record is new.

**Returns**

`bool`: Whether the record is new and should be inserted when calling [`save()`](/docs/api/yii/db/baseactiverecord/index.md#method-save).

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

```php
public function getOldAttribute(string $name): mixed
```

Returns the old value of the named attribute.

If this record is the result of a query and the attribute is not loaded,
`null` will be returned.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The attribute name |

**Returns**

`mixed`: The old attribute value. `null` if the attribute is not loaded before or does not exist.

**See also**

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

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

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

Returns the old attribute values.

**Returns**

`array`: The old attribute values (name-value pairs)

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

```php
public function getOldPrimaryKey(bool $asArray = false): mixed
```

Returns the old primary key value(s).

This refers to the primary key value that is populated into the record
after executing a find method (e.g. find(), findOne()).
The value remains unchanged even if the primary key attribute is manually assigned with a different value.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$asArray` | `bool` | Whether to return the primary key value as an array. If `true`, the return value will be an array with column name as key and column value as value. If this is `false` (default), a scalar value will be returned for non-composite primary key. |

**Returns**

`mixed`: The old primary key value. An array (column name => column value) is returned if the primary key is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if the key value is null).

**Throws**

- [`Exception`](/docs/api/yii/db/exception/index.md): if the AR model does not have a primary key

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

```php
public function getPrimaryKey(bool $asArray = false): mixed
```

Returns the primary key value(s).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$asArray` | `bool` | Whether to return the primary key value as an array. If `true`, the return value will be an array with column names as keys and column values as values. Note that for composite primary keys, an array will always be returned regardless of this parameter value. |

**Returns**

`mixed`: The primary key value. An array (column name => column value) is returned if the primary key is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if the key value is null).

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

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

Returns all populated related records.

**Returns**

`array`: An array of related records indexed by relation names.

**See also**

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

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

```php
public function getRelation(string $name, bool $throwException = true): yii\db\ActiveQueryInterface|yii\db\ActiveQuery|null
```

Returns the relation object with the specified name.

A relation is defined by a getter method which returns an [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md) object.
It can be declared in either the Active Record class itself or one of its behaviors.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive). |
| `$throwException` | `bool` | Whether to throw exception if the relation does not exist. |

**Returns**

[`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md)`|`[`ActiveQuery`](/docs/api/yii/db/activequery/index.md)`|null`: The relational query object. If the relation does not exist and `$throwException` is `false`, `null` will be returned.

**Throws**

- [`yii\base\InvalidArgumentException`](/docs/api/yii/base/invalidargumentexception/index.md): if the named relation does not exist.

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

```php
public function hasAttribute(string $name): bool
```

Returns a value indicating whether the model has an attribute with the specified name.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The name of the attribute |

**Returns**

`bool`: Whether the model has an attribute with the specified name.

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

```php
public function hasMany(class-string $class, array<string, string> $link): yii\db\ActiveQueryInterface
```

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` | The class name of the related record |
| `$link` | `array<string, string>` | 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**

[`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md): The relational query object.

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

```php
public function hasOne(class-string $class, array<string, string> $link): yii\db\ActiveQueryInterface
```

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` | The class name of the related record |
| `$link` | `array<string, string>` | 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**

[`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md): The relational query object.

### 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/baseactiverecord/index.md#event-EVENT_INIT) event.

**Returns**

`mixed`

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

```php
public static function instantiate(array $row): static
```

Creates an active record instance.

This method is called together with [`populateRecord()`](/docs/api/yii/db/baseactiverecord/index.md#method-populateRecord) by [`ActiveQuery`](/docs/api/yii/db/activequery/index.md).
It is not meant to be used for creating new records directly.

You may override this method if the instance being created
depends on the row data to be populated into the record.
For example, by creating a record based on the value of a column,
you may implement the so-called single-table inheritance mapping.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$row` | `array` | Row data to be populated into the record. |

**Returns**

`static`: The newly created active record

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

```php
public function isAttributeChanged(string $name, bool $identical = true): bool
```

Returns a value indicating whether the named attribute has been changed.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The name of the attribute. |
| `$identical` | `bool` | Whether the comparison of new and old value is made for identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison. This parameter is available since version 2.0.4. |

**Returns**

`bool`: Whether the attribute has been changed

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

```php
public static function isPrimaryKey(array $keys): bool
```

Returns a value indicating whether the given set of attributes represents the primary key for this model.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$keys` | `array` | The set of attributes to check |

**Returns**

`bool`: Whether the given set of attributes represents the primary key for this model

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

```php
public function isRelationPopulated(string $name): bool
```

Check whether the named relation has been populated with records.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive). |

**Returns**

`bool`: Whether relation has been populated with records.

**See also**

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

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

```php
public function link(string $name, yii\db\ActiveRecordInterface $model, array $extraColumns = []): mixed
```

Establishes the relationship between two models.

The relationship is established by setting the foreign key value(s) in one model
to be the corresponding primary key value(s) in the other model.
The model with the foreign key will be saved into database **without** performing validation
and **without** events/behaviors.

If the relationship involves a junction table, a new row will be inserted into the
junction table which contains the primary key values from both models.

Note that this method requires that the primary key value is not null.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method. |
| `$model` | [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md) | The model to be linked with the current one. |
| `$extraColumns` | `array` | Additional column values to be saved into the junction table. This parameter is only meaningful for a relationship involving a junction table (i.e., a relation set with [`ActiveRelationTrait::via()`](/docs/api/yii/db/activerelationtrait/index.md#method-via) or [`ActiveQuery::viaTable()`](/docs/api/yii/db/activequery/index.md#method-viaTable).) |

**Returns**

`mixed`

**Throws**

- [`yii\base\InvalidCallException`](/docs/api/yii/base/invalidcallexception/index.md): if the method is unable to link two models.

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

```php
public function loadRelations(string|array $relationNames, bool $asArray = false): mixed
```

Eager loads related models for the already loaded primary model.

Helps to reduce the number of queries performed against database if some related models are only used
when a specific condition is met. For example:

```
$customer = Customer::find()->where(['id' => 123])->one();
if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
    $customer->loadRelations('orders.items');
}
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$relationNames` | `string\|array` | The names of the relations of this model to be loaded from database. See [`ActiveQueryInterface::with()`](/docs/api/yii/db/activequeryinterface/index.md#method-with) on how to specify this argument. |
| `$asArray` | `bool` | Whether to load each relation as an array or an object (if the relation itself does not specify that). |

**Returns**

`mixed`

**Since**

2.0.50

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

```php
public static function loadRelationsFor(yii\db\TModels &$models, string|array $relationNames, bool $asArray = false): mixed
```

Eager loads related models for the already loaded primary models.

Helps to reduce the number of queries performed against database if some related models are only used
when a specific condition is met. For example:

```
$customers = Customer::find()->where(['country_id' => 123])->all();
if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
    Customer::loadRelationsFor($customers, 'orders.items');
}
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$models` | `yii\db\TModels` | Array of primary models. Each model should have the same type and can be: - an active record instance; - active record instance represented by array (i.e. active record was loaded using [`ActiveQuery::asArray()`](/docs/api/yii/db/activequery/index.md#method-asArray)). |
| `$relationNames` | `string\|array` | The names of the relations of primary models to be loaded from database. See [`ActiveQueryInterface::with()`](/docs/api/yii/db/activequeryinterface/index.md#method-with) on how to specify this argument. |
| `$asArray` | `bool` | Whether to load each related model as an array or an object (if the relation itself does not specify that). |

**Returns**

`mixed`

**Since**

2.0.50

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

```php
public function markAttributeDirty(string $name): mixed
```

Marks an attribute dirty.

This method may be called to force updating a record when calling [`update()`](/docs/api/yii/db/baseactiverecord/index.md#method-update),
even if there is no change being made to the record.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The attribute name |

**Returns**

`mixed`

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

```php
public function offsetExists(mixed $offset): bool
```

Returns whether there is an element at the specified offset.

This method is required by the interface [`ArrayAccess`](https://www.php.net/manual/en/class.arrayaccess.php).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$offset` | `mixed` | The offset to check on |

**Returns**

`bool`: Whether there is an element at the specified offset.

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

```php
public function offsetUnset(mixed $offset): mixed
```

Sets the element value at the specified offset to null.

This method is required by the SPL interface [`ArrayAccess`](https://www.php.net/manual/en/class.arrayaccess.php).
It is implicitly called when you use something like `unset($model[$offset])`.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$offset` | `mixed` | The offset to unset element |

**Returns**

`mixed`

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

```php
public function optimisticLock(): string|null
```

Returns the name of the column that stores the lock version for implementing optimistic locking.

Optimistic locking allows multiple users to access the same record for edits and avoids
potential conflicts. In case when a user attempts to save the record upon some staled data
(because another user has modified the data), a [`StaleObjectException`](/docs/api/yii/db/staleobjectexception/index.md) exception will be thrown,
and the update or deletion is skipped.

Optimistic locking is only supported by [`update()`](/docs/api/yii/db/baseactiverecord/index.md#method-update) and [`delete()`](/docs/api/yii/db/baseactiverecord/index.md#method-delete).

To use Optimistic locking:

1. Create a column to store the version number of each row. The column type should be `BIGINT DEFAULT 0`.
   Override this method to return the name of this column.
2. Ensure the version value is submitted and loaded to your model before any update or delete.
   Or add [OptimisticLockBehavior](/docs/api/yii/behaviors/optimisticlockbehavior/index.md) to your model
   class in order to automate the process.
3. In the Web form that collects the user input, add a hidden field that stores
   the lock version of the record being updated.
4. In the controller action that does the data updating, try to catch the [`StaleObjectException`](/docs/api/yii/db/staleobjectexception/index.md)
   and implement necessary business logic (e.g. merging the changes, prompting stated data)
   to resolve the conflict.

**Returns**

`string|null`: The column name that stores the lock version of a table row. If `null` is returned (default implemented), optimistic locking will not be supported.

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

```php
public static function populateRecord(yii\db\BaseActiveRecord $record, array $row): 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` | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) | 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` | `array` | Attribute values (name => value) |

**Returns**

`mixed`

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

```php
public function populateRelation(string $name, yii\db\ActiveRecordInterface|array|null $records): mixed
```

Populates the named relation with the related records.

Note that this method does not check if the relation exists or not.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive). |
| `$records` | [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md)`\|array\|null` | The related records to be populated into the relation. |

**Returns**

`mixed`

**See also**

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

### 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.

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

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

Saves the current record.

This method will call [`insert()`](/docs/api/yii/db/activerecordinterface/index.md#method-insert) when [`$isNewRecord`](/docs/api/yii/db/baseactiverecord/index.md#property-isNewRecord) is `true`, or [`update()`](/docs/api/yii/db/baseactiverecord/index.md#method-update)
when [`$isNewRecord`](/docs/api/yii/db/baseactiverecord/index.md#property-isNewRecord) is `false`.

For example, to save a customer record:

```
$customer = new Customer; // or $customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->save();
```

**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 attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved. |

**Returns**

`bool`: Whether the saving succeeded (i.e. no validation errors occurred).

**Throws**

- [`Exception`](/docs/api/yii/db/exception/index.md): in case update or insert failed.

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

```php
public function setAttribute(string $name, mixed $value): mixed
```

Sets the named attribute value.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The attribute name |
| `$value` | `mixed` | The attribute value. |

**Returns**

`mixed`

**Throws**

- [`yii\base\InvalidArgumentException`](/docs/api/yii/base/invalidargumentexception/index.md): if the named attribute does not exist.

**See also**

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

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

```php
public function setIsNewRecord(bool $value): mixed
```

Sets the value indicating whether the record is new.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$value` | `bool` | Whether the record is new and should be inserted when calling [`save()`](/docs/api/yii/db/baseactiverecord/index.md#method-save). |

**Returns**

`mixed`

**See also**

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

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

```php
public function setOldAttribute(string $name, mixed $value): mixed
```

Sets the old value of the named attribute.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The attribute name |
| `$value` | `mixed` | The old attribute value. |

**Returns**

`mixed`

**Throws**

- [`yii\base\InvalidArgumentException`](/docs/api/yii/base/invalidargumentexception/index.md): if the named attribute does not exist.

**See also**

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

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

```php
public function setOldAttributes(array|null $values): mixed
```

Sets the old attribute values.

All existing old attribute values will be discarded.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$values` | `array\|null` | Old attribute values to be set. If set to `null` this record is considered to be [new](/docs/api/yii/db/baseactiverecord/index.md#property-isNewRecord). |

**Returns**

`mixed`

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

```php
public function unlink(string $name, yii\db\ActiveRecordInterface $model, bool $delete = false): mixed
```

Destroys the relationship between two models.

The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
Otherwise, the foreign key will be set `null` and the model will be saved without validation.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method. |
| `$model` | [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md) | The model to be unlinked from the current one. You have to make sure that the model is really related with the current model as this method does not check this. |
| `$delete` | `bool` | Whether to delete the model that contains the foreign key. If `false`, the model's foreign key will be set `null` and saved. If `true`, the model containing the foreign key will be deleted. |

**Returns**

`mixed`

**Throws**

- [`yii\base\InvalidCallException`](/docs/api/yii/base/invalidcallexception/index.md): if the models cannot be unlinked
- [`Exception`](/docs/api/yii/db/exception/index.md)
- [`StaleObjectException`](/docs/api/yii/db/staleobjectexception/index.md)

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

```php
public function unlinkAll(string $name, bool $delete = false): mixed
```

Destroys the relationship in current model.

The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
Otherwise, the foreign key will be set `null` and the model will be saved without validation.

Note that to destroy the relationship without removing records make sure your keys can be set to null

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method. |
| `$delete` | `bool` | Whether to delete the model that contains the foreign key. Note that the deletion will be performed using [`deleteAll()`](/docs/api/yii/db/baseactiverecord/index.md#method-deleteAll), which will not trigger any events on the related models. 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/activerecordinterface/index.md#method-find) the models first and then call [`delete()`](/docs/api/yii/db/baseactiverecord/index.md#method-delete) on each of them. |

**Returns**

`mixed`

### 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 attribute names 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.
- [`Exception`](/docs/api/yii/db/exception/index.md): in case update failed.

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

```php
public static function updateAll(array $attributes, string|array $condition = ''): 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');
```

**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. |

**Returns**

`int`: The number of rows updated

**Throws**

- [`yii\base\NotSupportedException`](/docs/api/yii/base/notsupportedexception/index.md): if not overridden

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

```php
public static function updateAllCounters(array $counters, string|array $condition = ''): 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]);
```

**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. |

**Returns**

`int`: The number of rows updated

**Throws**

- [`yii\base\NotSupportedException`](/docs/api/yii/base/notsupportedexception/index.md): if not overrided

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

```php
public function updateAttributes(array $attributes): int
```

Updates the specified attributes.

This method is a shortcut to [`update()`](/docs/api/yii/db/baseactiverecord/index.md#method-update) when data validation is not needed
and only a small set attributes need to be updated.

You may specify the attributes to be updated as name list or name-value pairs.
If the latter, the corresponding attribute values will be modified accordingly.
The method will then save the specified attributes into database.

Note that this method will **not** perform data validation and will **not** trigger events.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attributes` | `array` | The attributes (names or name-value pairs) to be updated |

**Returns**

`int`: The number of rows affected.

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

```php
public function updateCounters(array $counters): bool
```

Updates one or several counter columns for the current AR object.

Note that this method differs from [`updateAllCounters()`](/docs/api/yii/db/baseactiverecord/index.md#method-updateAllCounters) in that it only
saves counters for the current AR object.

An example usage is as follows:

```
$post = Post::findOne($id);
$post->updateCounters(['view_count' => 1]);
```

**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. |

**Returns**

`bool`: Whether the saving is successful

**See also**

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

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

```php
protected function createRelationQuery(string $class, array $link, bool $multiple): yii\db\ActiveQueryInterface
```

Creates a query instance for `has-one` or `has-many` relation.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$class` | `string` | The class name of the related record. |
| `$link` | `array` | The primary-foreign key constraint. |
| `$multiple` | `bool` | Whether this query represents a relation to more than one record. |

**Returns**

[`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md): The relational query object.

**Since**

2.0.12

**See also**

- [`hasOne()`](/docs/api/yii/db/baseactiverecord/index.md#method-hasOne)
- [`hasMany()`](/docs/api/yii/db/baseactiverecord/index.md#method-hasMany)

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

```php
protected function refreshInternal(yii\db\BaseActiveRecord $record): bool
```

Repopulates this active record with the latest data from a newly fetched instance.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$record` | [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) | The record to take attributes from. |

**Returns**

`bool`: Whether refresh was successful.

**Since**

2.0.13

**See also**

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

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

```php
protected function updateInternal(array|null $attributes = null): int|false
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attributes` | `array\|null` | Attributes to update |

**Returns**

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

**Throws**

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

**See also**

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