ActiveRecord

Type
Abstract Class
Namespace
craft\db
Inherits
craft\db\ActiveRecord » yii\db\ActiveRecord (opens new window) » yii\db\BaseActiveRecord (opens new window) » yii\base\Model (opens new window) » yii\base\Component (opens new window) » yii\base\BaseObject (opens new window)
Implements
ArrayAccess (opens new window), IteratorAggregate (opens new window), yii\base\Arrayable (opens new window), yii\base\Configurable (opens new window), yii\base\StaticInstanceInterface (opens new window), yii\db\ActiveRecordInterface (opens new window)
Uses traits
yii\base\ArrayableTrait (opens new window), yii\base\StaticInstanceTrait (opens new window)
Extended by
craft\records\Address, craft\records\Asset, craft\records\AssetIndexData, craft\records\AssetIndexingSession, craft\records\Category, craft\records\CategoryGroup, craft\records\CategoryGroup_SiteSettings, craft\records\CraftIdToken, craft\records\Element, craft\records\Element_SiteSettings, craft\records\Entry, craft\records\EntryType, craft\records\Field, craft\records\FieldGroup, craft\records\FieldLayout, craft\records\FieldLayoutField, craft\records\FieldLayoutTab, craft\records\GlobalSet, craft\records\GqlSchema, craft\records\GqlToken, craft\records\ImageTransform, craft\records\MatrixBlock, craft\records\MatrixBlockType, craft\records\Plugin, craft\records\Section, craft\records\Section_SiteSettings, craft\records\Session, craft\records\Site, craft\records\SiteGroup, craft\records\Structure, craft\records\StructureElement, craft\records\SystemMessage, craft\records\Tag, craft\records\TagGroup, craft\records\Token, craft\records\User, craft\records\UserGroup, craft\records\UserGroup_User, craft\records\UserPermission, craft\records\UserPermission_User, craft\records\UserPermission_UserGroup, craft\records\Volume, craft\records\VolumeFolder, craft\records\Widget
Since
3.0.0

Active Record base class.

View source (opens new window)

# Public Properties

Property Description
activeValidators (opens new window) yii\validators\Validator (opens new window) – The validators applicable to the current scenario (opens new window).
attributes (opens new window) array (opens new window) – Attribute values (name => value).
behaviors (opens new window) yii\base\Behavior (opens new window) – List of behaviors attached to this component.
dateCreated DateTime (opens new window), string (opens new window), null (opens new window) – Date created
dateUpdated DateTime (opens new window), string (opens new window), null (opens new window) – Date updated
dirtyAttributes (opens new window) array (opens new window) – The changed attribute values (name-value pairs).
errors (opens new window) array (opens new window) – Errors for all attributes or the specified attribute.
firstErrors (opens new window) array (opens new window) – The first errors.
isNewRecord (opens new window) boolean (opens new window) – Whether the record is new and should be inserted when calling save() (opens new window).
iterator (opens new window) ArrayIterator (opens new window) – An iterator for traversing the items in the list.
oldAttributes (opens new window) array (opens new window) – The old attribute values (name-value pairs).
oldPrimaryKey (opens new window) mixed – The old primary key value.
primaryKey (opens new window) mixed – The primary key value.
relatedRecords (opens new window) array (opens new window) – An array of related records indexed by relation names.
scenario (opens new window) string (opens new window) – The scenario that this model is in.
uid string (opens new window) – UUID
validators (opens new window) ArrayObject (opens new window), yii\validators\Validator (opens new window) – All the validators declared in the model.

# dateCreated

Type
DateTime (opens new window), string (opens new window), null (opens new window)
Default value
null

Date created

View source (opens new window)

# dateUpdated

Type
DateTime (opens new window), string (opens new window), null (opens new window)
Default value
null

Date updated

View source (opens new window)

# uid

Type
string (opens new window)
Default value
null

UUID

View source (opens new window)

# Public Methods

Method Description
__call() (opens new window) Calls the named method which is not a class method.
__clone() (opens new window) This method is called after the object is created by cloning an existing one.
__construct() (opens new window) Constructor.
__get() (opens new window) PHP getter magic method.
__isset() (opens new window) Checks if a property value is null.
__set() PHP setter magic method.
__unset() (opens new window) Sets a component property to be null.
activeAttributes() (opens new window) Returns the attribute names that are subject to validation in the current scenario.
addError() (opens new window) Adds a new error to the specified attribute.
addErrors() (opens new window) Adds a list of errors.
afterDelete() (opens new window) This method is invoked after deleting a record.
afterFind() (opens new window) This method is called when the AR object is created and populated with the query result.
afterRefresh() (opens new window) This method is called when the AR object is refreshed.
afterSave() (opens new window) This method is called at the end of inserting or updating a record.
afterValidate() (opens new window) This method is invoked after validation ends.
attachBehavior() (opens new window) Attaches a behavior to this component.
attachBehaviors() (opens new window) Attaches a list of behaviors to the component.
attributeHints() (opens new window) Returns the attribute hints.
attributeLabels() (opens new window) Returns the attribute labels.
attributes() (opens new window) Returns the list of all attribute names of the model.
beforeDelete() (opens new window) This method is invoked before deleting a record.
beforeSave() This method is called at the beginning of inserting or updating a record.
beforeValidate() (opens new window) This method is invoked before validation starts.
behaviors() Returns a list of behaviors that this component should behave as.
canGetProperty() (opens new window) Returns a value indicating whether a property can be read.
canSetProperty() (opens new window) Returns a value indicating whether a property can be set.
className() (opens new window) Returns the fully qualified name of this class.
clearErrors() (opens new window) Removes errors for all attributes or a single attribute.
createValidators() (opens new window) Creates validator objects based on the validation rules specified in rules() (opens new window).
delete() (opens new window) Deletes the table row corresponding to this active record.
deleteAll() (opens new window) Deletes rows in the table using the provided conditions.
detachBehavior() (opens new window) Detaches a behavior from the component.
detachBehaviors() (opens new window) Detaches all behaviors from the component.
ensureBehaviors() (opens new window) Makes sure that the behaviors declared in behaviors() (opens new window) are attached to this component.
equals() (opens new window) Returns a value indicating whether the given active record is the same as the current one.
extraFields() (opens new window) Returns the list of fields that can be expanded further and returned by toArray() (opens new window).
fields() (opens new window) Returns the list of fields that should be returned by default by toArray() (opens new window) when no specific fields are specified.
find() Creates an \craft\db\ActiveQueryInterface instance for query purpose.
findAll() (opens new window) Returns a list of active record models that match the specified primary key value(s) or a set of column values.
findBySql() See yii\db\ActiveRecord::findBySql() (opens new window) for more info.
findOne() (opens new window) Returns a single active record model instance by a primary key or an array of column values.
formName() (opens new window) Returns the form name that this model class should use.
generateAttributeLabel() (opens new window) Generates a user friendly attribute label based on the give attribute name.
getActiveValidators() (opens new window) Returns the validators applicable to the current scenario (opens new window).
getAttribute() (opens new window) Returns the named attribute value.
getAttributeHint() (opens new window) Returns the text hint for the specified attribute.
getAttributeLabel() (opens new window) Returns the text label for the specified attribute.
getAttributes() (opens new window) Returns attribute values.
getBehavior() (opens new window) Returns the named behavior object.
getBehaviors() (opens new window) Returns all behaviors attached to this component.
getDb() (opens new window) Returns the database connection used by this AR class.
getDirtyAttributes() (opens new window) Returns the attribute values that have been modified since they are loaded or saved most recently.
getErrorSummary() (opens new window) Returns the errors for all attributes as a one-dimensional array.
getErrors() (opens new window) Returns the errors for all attributes or a single attribute.
getFirstError() (opens new window) Returns the first error of the specified attribute.
getFirstErrors() (opens new window) Returns the first error of every attribute in the model.
getIsNewRecord() (opens new window) Returns a value indicating whether the current record is new.
getIterator() (opens new window) Returns an iterator for traversing the attributes in the model.
getOldAttribute() (opens new window) Returns the old value of the named attribute.
getOldAttributes() (opens new window) Returns the old attribute values.
getOldPrimaryKey() (opens new window) Returns the old primary key value(s).
getPrimaryKey() (opens new window) Returns the primary key value(s).
getRelatedRecords() (opens new window) Returns all populated related records.
getRelation() (opens new window) Returns the relation object with the specified name.
getScenario() (opens new window) Returns the scenario that this model is used in.
getTableSchema() (opens new window) Returns the schema information of the DB table associated with this AR class.
getValidators() (opens new window) Returns all the validators declared in rules() (opens new window).
hasAttribute() (opens new window) Returns a value indicating whether the model has an attribute with the specified name.
hasErrors() (opens new window) Returns a value indicating whether there is any validation error.
hasEventHandlers() (opens new window) Returns a value indicating whether there is any handler attached to the named event.
hasMany() See yii\db\BaseActiveRecord::hasMany() (opens new window) for more info.
hasMethod() (opens new window) Returns a value indicating whether a method is defined.
hasOne() See yii\db\BaseActiveRecord::hasOne() (opens new window) for more info.
hasProperty() (opens new window) Returns a value indicating whether a property is defined for this component.
init() (opens new window) Initializes the object.
insert() (opens new window) Inserts a row into the associated database table using the attribute values of this record.
instance() (opens new window) Returns static class instance, which can be used to obtain meta information.
instantiate() (opens new window) Creates an active record instance.
isAttributeActive() (opens new window) Returns a value indicating whether the attribute is active in the current scenario.
isAttributeChanged() (opens new window) Returns a value indicating whether the named attribute has been changed.
isAttributeRequired() (opens new window) Returns a value indicating whether the attribute is required.
isAttributeSafe() (opens new window) Returns a value indicating whether the attribute is safe for massive assignments.
isPrimaryKey() (opens new window) Returns a value indicating whether the given set of attributes represents the primary key for this model.
isRelationPopulated() (opens new window) Check whether the named relation has been populated with records.
isTransactional() (opens new window) Returns a value indicating whether the specified operation is transactional in the current scenario (opens new window).
link() (opens new window) Establishes the relationship between two models.
load() (opens new window) Populates the model with input data.
loadDefaultValues() (opens new window) Loads default values from database table schema.
loadMultiple() (opens new window) Populates a set of models with the data from end user.
markAttributeDirty() (opens new window) Marks an attribute dirty.
off() (opens new window) Detaches an existing event handler from this component.
offsetExists() (opens new window) Returns whether there is an element at the specified offset.
offsetGet() (opens new window) Returns the element at the specified offset.
offsetSet() (opens new window) Sets the element at the specified offset.
offsetUnset() (opens new window) Sets the element value at the specified offset to null.
on() (opens new window) Attaches an event handler to an event.
onUnsafeAttribute() (opens new window) This method is invoked when an unsafe attribute is being massively assigned.
optimisticLock() (opens new window) Returns the name of the column that stores the lock version for implementing optimistic locking.
populateRecord() (opens new window) Populates an active record object using a row of data from the database/storage.
populateRelation() (opens new window) Populates the named relation with the related records.
primaryKey() (opens new window) Returns the primary key name(s) for this AR class.
refresh() (opens new window) Repopulates this active record with the latest data.
rules() (opens new window) Returns the validation rules for attributes.
safeAttributes() (opens new window) Returns the attribute names that are safe to be massively assigned in the current scenario.
save() (opens new window) Saves the current record.
scenarios() (opens new window) Returns a list of scenarios and the corresponding active attributes.
setAttribute() Sets the named attribute value.
setAttributes() (opens new window) Sets the attribute values in a massive way.
setIsNewRecord() (opens new window) Sets the value indicating whether the record is new.
setOldAttribute() (opens new window) Sets the old value of the named attribute.
setOldAttributes() (opens new window) Sets the old attribute values.
setScenario() (opens new window) Sets the scenario for the model.
tableName() (opens new window) Declares the name of the database table associated with this AR class.
toArray() (opens new window) Converts the model into an array.
transactions() (opens new window) Declares which DB operations should be performed within a transaction in different scenarios.
trigger() (opens new window) Triggers an event.
unlink() (opens new window) Destroys the relationship between two models.
unlinkAll() (opens new window) Destroys the relationship in current model.
update() (opens new window) Saves the changes to this active record into the associated database table.
updateAll() (opens new window) Updates the whole table using the provided attribute values and conditions.
updateAllCounters() (opens new window) Updates the whole table using the provided counter changes and conditions.
updateAttributes() (opens new window) Updates the specified attributes.
updateCounters() (opens new window) Updates one or several counter columns for the current AR object.
validate() (opens new window) Performs the data validation.
validateMultiple() (opens new window) Validates multiple models.

# __set()

Since
3.4.0

PHP setter magic method.

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

View source (opens new window)

Arguments

# beforeSave()

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

The default implementation will trigger an EVENT_BEFORE_INSERT (opens new window) event when $insert is true, or an EVENT_BEFORE_UPDATE (opens new window) 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;
}

View source (opens new window)

Arguments

  • $insert (boolean (opens new window)) – Whether this method called while inserting a record. If false, it means the method is called while updating a record.

Returns

boolean (opens new window) – Whether the insertion or updating should continue. If false, the insertion or updating will be cancelled.

# behaviors()

Since
3.4.0

Returns a list of behaviors that this component should behave as.

Child classes may override this method to specify the behaviors they want to behave as.

The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

Note that a behavior class must extend from \craft\db\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() (opens new window) or be detached using detachBehavior() (opens new window). Anonymous behaviors can not be retrieved or detached.

Behaviors declared in this method will be attached to the component automatically (on demand).

View source (opens new window)

Returns

array (opens new window) – The behavior configurations.

# find()

Creates an \craft\db\ActiveQueryInterface instance for query purpose.

The returned \craft\db\ActiveQueryInterface instance can be further customized by calling methods defined in \craft\db\ActiveQueryInterface before one() or all() is called to return populated ActiveRecord instances. For example,

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

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

This method is also called by yii\db\BaseActiveRecord::hasOne() (opens new window) and yii\db\BaseActiveRecord::hasMany() (opens new window) to create a relational query.

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

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

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

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

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

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




[View source](https://github.com/craftcms/cms/blob/main/src/db/ActiveRecord.php#L42-L45)



#### Returns

[craft\db\ActiveQuery](craft-db-activequery.md) – The newly created [craft\db\ActiveQuery](craft-db-activequery.md) instance.



### `findBySql()`





See [yii\db\ActiveRecord::findBySql()](https://www.yiiframework.com/doc/api/2.0/yii-db-activerecord#findBySql()-detail) for more info.




[View source](https://github.com/craftcms/cms/blob/main/src/db/ActiveRecord.php)


#### Arguments

- `$sql`
- `$params`

#### Returns

[craft\db\ActiveQuery](craft-db-activequery.md)### `hasMany()`





See [yii\db\BaseActiveRecord::hasMany()](https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#hasMany()-detail) for more info.




[View source](https://github.com/craftcms/cms/blob/main/src/db/ActiveRecord.php)


#### Arguments

- `$class`
- `$link`

#### Returns

[craft\db\ActiveQuery](craft-db-activequery.md)### `hasOne()`





See [yii\db\BaseActiveRecord::hasOne()](https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#hasOne()-detail) for more info.




[View source](https://github.com/craftcms/cms/blob/main/src/db/ActiveRecord.php)


#### Arguments

- `$class`
- `$link`

#### Returns

[craft\db\ActiveQuery](craft-db-activequery.md)### `setAttribute()`



Since
:  3.4.0



Sets the named attribute value.








[View source](https://github.com/craftcms/cms/blob/main/src/db/ActiveRecord.php#L75-L79)


#### Arguments

- `$name` ([string](https://php.net/language.types.string)) – The attribute name
- `$value` (`mixed`) – The attribute value.


#### Throws

- [yii\base\InvalidArgumentException](https://www.yiiframework.com/doc/api/2.0/yii-base-invalidargumentexception)\
  if the named attribute does not exist.




## Protected Methods

| Method                                                                                                                                                      | Description
| ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| [createRelationQuery()](https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#createRelationQuery()-detail "Defined by yii\db\BaseActiveRecord") | Creates a query instance for `has-one` or `has-many` relation.
| [deleteInternal()](https://www.yiiframework.com/doc/api/2.0/yii-db-activerecord#deleteInternal()-detail "Defined by yii\db\ActiveRecord")                   | Deletes an ActiveRecord without considering transaction.
| [extractFieldsFor()](https://www.yiiframework.com/doc/api/2.0/yii-base-arrayabletrait#extractFieldsFor()-detail "Defined by yii\base\ArrayableTrait")       | 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".
| [extractRootFields()](https://www.yiiframework.com/doc/api/2.0/yii-base-arrayabletrait#extractRootFields()-detail "Defined by yii\base\ArrayableTrait")     | Extracts the root field names from nested fields.
| [insertInternal()](https://www.yiiframework.com/doc/api/2.0/yii-db-activerecord#insertInternal()-detail "Defined by yii\db\ActiveRecord")                   | Inserts an ActiveRecord into DB without considering transaction.
| [prepareForDb()](craft-db-activerecord.md#method-preparefordb)                                                                                              | Sets the `dateCreated`, `dateUpdated`, and `uid` attributes on the record.
| [refreshInternal()](https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#refreshInternal()-detail "Defined by yii\db\BaseActiveRecord")         | Repopulates this active record with the latest data from a newly fetched instance.
| [resolveFields()](https://www.yiiframework.com/doc/api/2.0/yii-base-arrayabletrait#resolveFields()-detail "Defined by yii\base\ArrayableTrait")             | Determines which fields can be returned by [toArray()](https://www.yiiframework.com/doc/api/2.0/yii-base-arrayabletrait#toArray()-detail).
| [updateInternal()](https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#updateInternal()-detail "Defined by yii\db\BaseActiveRecord")           |

### `prepareForDb()`



Since
:  3.1.0



Sets the `dateCreated`, `dateUpdated`, and `uid` attributes on the record.




[View source](https://github.com/craftcms/cms/blob/main/src/db/ActiveRecord.php#L95-L128)








## Constants

| Constant           | Description
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| `OP_ALL`           | All three operations: insert, update, delete.
| `OP_DELETE`        | The delete operation. This is mainly used when overriding [transactions()](https://www.yiiframework.com/doc/api/2.0/yii-db-activerecord#transactions()-detail) to specify which operations are transactional.
| `OP_INSERT`        | The insert operation. This is mainly used when overriding [transactions()](https://www.yiiframework.com/doc/api/2.0/yii-db-activerecord#transactions()-detail) to specify which operations are transactional.
| `OP_UPDATE`        | The update operation. This is mainly used when overriding [transactions()](https://www.yiiframework.com/doc/api/2.0/yii-db-activerecord#transactions()-detail) to specify which operations are transactional.
| `SCENARIO_DEFAULT` | The name of the default scenario.


## Events

### EVENT_DEFINE_BEHAVIORS



Type
:  [craft\events\DefineBehaviorsEvent](craft-events-definebehaviorsevent.md)

Since
:  3.4.0



The event that is triggered when defining the class behaviors

See also [behaviors()](craft-db-activerecord.md#method-behaviors)

---