Skip to content
PHP Ecosystem
Explore

BaseActiveRecord

API reference › yii › db › BaseActiveRecord

1 subclass

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

See ActiveRecord for a concrete implementation.

PropertyTypeDescriptionDefined by
$activeValidators read-onlyyii\validators\Validator[]The validators applicable to the current $scenario.yii\base\Model
$attributesarray<string, mixed>Attribute values (name => value).yii\base\Model
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$dirtyAttributes read-onlyarrayThe changed attribute values (name-value pairs).BaseActiveRecord
$errors read-onlyarray<string, string[]>Errors for all attributes.yii\base\Model
$firstErrors read-onlyarray<string, string>The first errors.yii\base\Model
$isNewRecordboolWhether the record is new and should be inserted when calling save().BaseActiveRecord
$iterator read-onlyArrayIterator<string, mixed>An iterator for traversing the items in the list.yii\base\Model
$oldAttributesarray|nullOld attribute values to be set.BaseActiveRecord
$oldPrimaryKey read-onlymixedThe old primary key value.BaseActiveRecord
$primaryKey read-onlymixedThe primary key value.BaseActiveRecord
$relatedRecords read-onlyarrayAn array of related records indexed by relation names.BaseActiveRecord
$scenariostringThe scenario that this model is in.yii\base\Model
$validators read-onlyArrayObject<int, yii\validators\Validator>|yii\validators\Validator[]All the validators declared in the model.yii\base\Model
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Model
__get()PHP getter magic method.BaseActiveRecord
__isset()Checks if a property value is null.BaseActiveRecord
__set()PHP setter magic method.BaseActiveRecord
__unset()Sets a component property to be null.BaseActiveRecord
activeAttributes()Returns the attribute names that are subject to validation in the current scenario.yii\base\Model
addError()Adds a new error to the specified attribute.yii\base\Model
addErrors()Adds a list of errors.yii\base\Model
afterDelete()This method is invoked after deleting a record.BaseActiveRecord
afterFind()This method is called when the AR object is created and populated with the query result.BaseActiveRecord
afterRefresh()This method is called when the AR object is refreshed.BaseActiveRecord
afterSave()This method is called at the end of inserting or updating a record.BaseActiveRecord
afterValidate()This method is invoked after validation ends.yii\base\Model
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
attributeHints()Returns the attribute hints.yii\base\Model
attributeLabels()Returns the attribute labels.yii\base\Model
attributes()Returns the list of attribute names.yii\base\Model
beforeDelete()This method is invoked before deleting a record.BaseActiveRecord
beforeSave()This method is called at the beginning of inserting or updating a record.BaseActiveRecord
beforeValidate()This method is invoked before validation starts.yii\base\Model
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
canGetProperty()Returns a value indicating whether a property can be read.BaseActiveRecord
canSetOldAttribute()Returns if the old named attribute can be set.BaseActiveRecord
canSetProperty()Returns a value indicating whether a property can be set.BaseActiveRecord
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
clearErrors()Removes errors for all attributes or a single attribute.yii\base\Model
createValidators()Creates validator objects based on the validation rules specified in rules().yii\base\Model
delete()Deletes the table row corresponding to this active record.BaseActiveRecord
deleteAll() staticDeletes rows in the table using the provided conditions.BaseActiveRecord
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
equals()Returns a value indicating whether the given active record is the same as the current one.BaseActiveRecord
extraFields()Returns the list of fields that can be expanded further and returned by toArray().BaseActiveRecord
fields()Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.BaseActiveRecord
find() static abstractCreates an ActiveQueryInterface instance for query purpose.ActiveRecordInterface
findAll() staticReturns a list of active record models that match the specified primary key value(s) or a set of column values.BaseActiveRecord
findOne() staticReturns a single active record model instance by a primary key or an array of column values.BaseActiveRecord
formName()Returns the form name that this model class should use.yii\base\Model
generateAttributeLabel()Generates a user friendly attribute label based on the give attribute name.yii\base\Model
getActiveValidators()Returns the validators applicable to the current $scenario.yii\base\Model
getAttribute()Returns the named attribute value.BaseActiveRecord
getAttributeHint()Returns the text hint for the specified attribute.BaseActiveRecord
getAttributeLabel()Returns the text label for the specified attribute.BaseActiveRecord
getAttributes()Returns attribute values.yii\base\Model
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getDb() static abstractReturns the connection used by this AR class.ActiveRecordInterface
getDirtyAttributes()Returns the attribute values that have been modified since they are loaded or saved most recently.BaseActiveRecord
getErrors()Returns the errors for all attributes or a single attribute.yii\base\Model
getErrorSummary()Returns the errors for all attributes as a one-dimensional array.yii\base\Model
getFirstError()Returns the first error of the specified attribute.yii\base\Model
getFirstErrors()Returns the first error of every attribute in the model.yii\base\Model
getIsNewRecord()Returns a value indicating whether the current record is new.BaseActiveRecord
getIterator()Returns an iterator for traversing the attributes in the model.yii\base\Model
getOldAttribute()Returns the old value of the named attribute.BaseActiveRecord
getOldAttributes()Returns the old attribute values.BaseActiveRecord
getOldPrimaryKey()Returns the old primary key value(s).BaseActiveRecord
getPrimaryKey()Returns the primary key value(s).BaseActiveRecord
getRelatedRecords()Returns all populated related records.BaseActiveRecord
getRelation()Returns the relation object with the specified name.BaseActiveRecord
getScenario()Returns the scenario that this model is used in.yii\base\Model
getValidators()Returns all the validators declared in rules().yii\base\Model
hasAttribute()Returns a value indicating whether the model has an attribute with the specified name.BaseActiveRecord
hasErrors()Returns a value indicating whether there is any validation error.yii\base\Model
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMany()Declares a has-many relation.BaseActiveRecord
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasOne()Declares a has-one relation.BaseActiveRecord
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the object.BaseActiveRecord
insert() abstractInserts the record into the database using the attribute values of this record.ActiveRecordInterface
instance() staticReturns static class instance, which can be used to obtain meta information.yii\base\StaticInstanceTrait
instantiate() staticCreates an active record instance.BaseActiveRecord
isAttributeActive()Returns a value indicating whether the attribute is active in the current scenario.yii\base\Model
isAttributeChanged()Returns a value indicating whether the named attribute has been changed.BaseActiveRecord
isAttributeRequired()Returns a value indicating whether the attribute is required.yii\base\Model
isAttributeSafe()Returns a value indicating whether the attribute is safe for massive assignments.yii\base\Model
isPrimaryKey() staticReturns a value indicating whether the given set of attributes represents the primary key for this model.BaseActiveRecord
isRelationPopulated()Check whether the named relation has been populated with records.BaseActiveRecord
link()Establishes the relationship between two models.BaseActiveRecord
load()Populates the model with input data.yii\base\Model
loadMultiple() staticPopulates a set of models with the data from end user.yii\base\Model
loadRelations()Eager loads related models for the already loaded primary model.BaseActiveRecord
loadRelationsFor() staticEager loads related models for the already loaded primary models.BaseActiveRecord
markAttributeDirty()Marks an attribute dirty.BaseActiveRecord
off()Detaches an existing event handler from this component.yii\base\Component
offsetExists()Returns whether there is an element at the specified offset.BaseActiveRecord
offsetGet()Returns the element at the specified offset.yii\base\Model
offsetSet()Sets the element at the specified offset.yii\base\Model
offsetUnset()Sets the element value at the specified offset to null.BaseActiveRecord
on()Attaches an event handler to an event.yii\base\Component
onUnsafeAttribute()This method is invoked when an unsafe attribute is being massively assigned.yii\base\Model
optimisticLock()Returns the name of the column that stores the lock version for implementing optimistic locking.BaseActiveRecord
populateRecord() staticPopulates an active record object using a row of data from the database/storage.BaseActiveRecord
populateRelation()Populates the named relation with the related records.BaseActiveRecord
primaryKey() static abstractReturns the primary key name(s) for this AR class.ActiveRecordInterface
refresh()Repopulates this active record with the latest data.BaseActiveRecord
rules()Returns the validation rules for attributes.yii\base\Model
safeAttributes()Returns the attribute names that are safe to be massively assigned in the current scenario.yii\base\Model
save()Saves the current record.BaseActiveRecord
scenarios()Returns a list of scenarios and the corresponding active attributes.yii\base\Model
setAttribute()Sets the named attribute value.BaseActiveRecord
setAttributes()Sets the attribute values in a massive way.yii\base\Model
setIsNewRecord()Sets the value indicating whether the record is new.BaseActiveRecord
setOldAttribute()Sets the old value of the named attribute.BaseActiveRecord
setOldAttributes()Sets the old attribute values.BaseActiveRecord
setScenario()Sets the scenario for the model.yii\base\Model
toArray()Converts the model into an array.yii\base\ArrayableTrait
trigger()Triggers an event.yii\base\Component
unlink()Destroys the relationship between two models.BaseActiveRecord
unlinkAll()Destroys the relationship in current model.BaseActiveRecord
update()Saves the changes to this active record into the associated database table.BaseActiveRecord
updateAll() staticUpdates the whole table using the provided attribute values and conditions.BaseActiveRecord
updateAllCounters() staticUpdates the whole table using the provided counter changes and conditions.BaseActiveRecord
updateAttributes()Updates the specified attributes.BaseActiveRecord
updateCounters()Updates one or several counter columns for the current AR object.BaseActiveRecord
validate()Performs the data validation.yii\base\Model
validateMultiple() staticValidates multiple models.yii\base\Model
createRelationQuery() protectedCreates a query instance for has-one or has-many relation.BaseActiveRecord
extractFieldsFor() protectedExtract 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
extractRootFields() protectedExtracts the root field names from nested fields.yii\base\ArrayableTrait
refreshInternal() protectedRepopulates this active record with the latest data from a newly fetched instance.BaseActiveRecord
resolveFields() protectedDetermines which fields can be returned by toArray().yii\base\ArrayableTrait
updateInternal() protectedBaseActiveRecord
EventTypeDescriptionDefined by
EVENT_INITyii\db\EventAn event that is triggered when the record is initialized via init(). Event name: 'init'.BaseActiveRecord
EVENT_AFTER_FINDyii\db\EventAn event that is triggered after the record is created and populated with query result. Event name: 'afterFind'.BaseActiveRecord
EVENT_BEFORE_INSERTyii\base\ModelEventAn event that is triggered before inserting a record. Event name: 'beforeInsert'.BaseActiveRecord
EVENT_AFTER_INSERTAfterSaveEventAn event that is triggered after a record is inserted. Event name: 'afterInsert'.BaseActiveRecord
EVENT_BEFORE_UPDATEyii\base\ModelEventAn event that is triggered before updating a record. Event name: 'beforeUpdate'.BaseActiveRecord
EVENT_AFTER_UPDATEAfterSaveEventAn event that is triggered after a record is updated. Event name: 'afterUpdate'.BaseActiveRecord
EVENT_BEFORE_DELETEyii\base\ModelEventAn event that is triggered before deleting a record. Event name: 'beforeDelete'.BaseActiveRecord
EVENT_AFTER_DELETEyii\db\EventAn event that is triggered after a record is deleted. Event name: 'afterDelete'.BaseActiveRecord
EVENT_AFTER_REFRESHyii\db\EventAn event that is triggered after a record is refreshed. Event name: 'afterRefresh'. Available since 2.0.8.BaseActiveRecord
EVENT_BEFORE_VALIDATEyii\base\ModelEventAn event raised at the beginning of validate(). Event name: 'beforeValidate'.yii\base\Model
EVENT_AFTER_VALIDATEyii\base\EventAn event raised at the end of validate() Event name: 'afterValidate'.yii\base\Model
ConstantValueDescriptionDefined by
SCENARIO_DEFAULT'default'The name of the default scenario.yii\base\Model
public array|null $oldAttributes

Old attribute values to be set.

If set to null this record is considered to be new.

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

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

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

ParameterTypeDescription
$namestringProperty name

Returns

mixed: Property value

Throws

See also

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

ParameterTypeDescription
$namestringThe property name or the event name

Returns

bool: Whether the property value is null

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

ParameterTypeDescription
$namestringProperty name
$valuemixedProperty value

Returns

mixed

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

ParameterTypeDescription
$namestringThe property name or the event name

Returns

mixed

public function afterDelete(): mixed

This method is invoked after deleting a record.

The default implementation raises the 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

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 event. When overriding this method, make sure you call the parent implementation to ensure the event is triggered.

Returns

mixed

public function afterRefresh(): mixed

This method is called when the AR object is refreshed.

The default implementation will trigger an 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

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 event when $insert is true, or an EVENT_AFTER_UPDATE event if $insert is false. The event class used is AfterSaveEvent. When overriding this method, make sure you call the parent implementation so that the event is triggered.

Parameters

ParameterTypeDescription
$insertboolWhether this method called while inserting a record. If false, it means the method is called while updating a record.
$changedAttributesarrayThe 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 to facilitate attribute typecasting. See https://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting.

Returns

mixed

public function beforeDelete(): bool

This method is invoked before deleting a record.

The default implementation raises the 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.

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 event when $insert is true, or an 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

ParameterTypeDescription
$insertboolWhether 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.

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

ParameterTypeDescription
$namemixedThe property name
$checkVarsmixedWhether to treat member variables as properties
$checkBehaviorsmixedWhether to treat behaviors’ properties as properties of this component

Returns

bool: Whether the property can be read

public function canSetOldAttribute(string $name): bool

Returns if the old named attribute can be set.

Parameters

ParameterTypeDescription
$namestringThe attribute name

Returns

bool: Whether the old attribute can be set

See also

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

ParameterTypeDescription
$namemixedThe property name
$checkVarsmixedWhether to treat member variables as properties
$checkBehaviorsmixedWhether to treat behaviors’ properties as properties of this component

Returns

bool: Whether the property can be written

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(). If the method returns false, it will skip the rest of the steps;
  2. delete the record from the database;
  3. call afterDelete().

In the above step 1 and 3, events named EVENT_BEFORE_DELETE and 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

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

ParameterTypeDescription
$conditionstring|array|nullThe conditions that will be put in the WHERE part of the DELETE SQL. Please refer to Query::where() on how to specify this parameter.

Returns

int: The number of rows deleted

Throws

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 they are also considered not equal.

Parameters

ParameterTypeDescription
$recordActiveRecordInterfaceRecord to compare to

Returns

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

public function extraFields(): array

Returns the list of fields that can be expanded further and returned by toArray().

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

This method is similar to fields() except that the list of fields returned by this method are not returned by default by toArray(). Only when field names to be expanded are explicitly specified when calling 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() on the format of the return value.

public function fields(): array

Returns the list of fields that should be returned by default by 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().

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 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() indexed by the same attribute names.

Returns

array: The list of field names or field definitions.

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 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() in combination with 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

ParameterTypeDescription
$conditionmixedPrimary key value or a set of column values

Returns

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

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 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() in combination with 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

ParameterTypeDescription
$conditionmixedPrimary key value or a set of column values

Returns

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

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

ParameterTypeDescription
$namestringThe attribute name

Returns

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

See also

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

ParameterTypeDescription
$attributestringThe attribute name

Returns

string: The attribute hint

Since

2.0.4

See also

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() 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

ParameterTypeDescription
$attributestringThe attribute name

Returns

string: The attribute label

See also

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

ParameterTypeDescription
$namesstring[]|nullThe names of the attributes whose values may be returned if they are changed recently. If null, attributes() will be used.

Returns

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

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().

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

ParameterTypeDescription
$namestringThe attribute name

Returns

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

See also

public function getOldAttributes(): array

Returns the old attribute values.

Returns

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

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

ParameterTypeDescription
$asArrayboolWhether 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: if the AR model does not have a primary key
public function getPrimaryKey(bool $asArray = false): mixed

Returns the primary key value(s).

Parameters

ParameterTypeDescription
$asArrayboolWhether 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).

public function getRelatedRecords(): array

Returns all populated related records.

Returns

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

See also

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 object. It can be declared in either the Active Record class itself or one of its behaviors.

Parameters

ParameterTypeDescription
$namestringThe relation name, e.g. orders for a relation defined via getOrders() method (case-sensitive).
$throwExceptionboolWhether to throw exception if the relation does not exist.

Returns

ActiveQueryInterface|ActiveQuery|null: The relational query object. If the relation does not exist and $throwException is false, null will be returned.

Throws

public function hasAttribute(string $name): bool

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

Parameters

ParameterTypeDescription
$namestringThe name of the attribute

Returns

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

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 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 to further customize the relation.

Parameters

ParameterTypeDescription
$classclass-stringThe class name of the related record
$linkarray<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: The relational query object.

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 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 to further customize the relation.

Parameters

ParameterTypeDescription
$classclass-stringThe class name of the related record
$linkarray<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: The relational query object.

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

Returns

mixed

public static function instantiate(array $row): static

Creates an active record instance.

This method is called together with populateRecord() by ActiveQuery. 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

ParameterTypeDescription
$rowarrayRow data to be populated into the record.

Returns

static: The newly created active record

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

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

Parameters

ParameterTypeDescription
$namestringThe name of the attribute.
$identicalboolWhether 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

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

ParameterTypeDescription
$keysarrayThe set of attributes to check

Returns

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

public function isRelationPopulated(string $name): bool

Check whether the named relation has been populated with records.

Parameters

ParameterTypeDescription
$namestringThe 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

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

ParameterTypeDescription
$namestringThe case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method.
$modelActiveRecordInterfaceThe model to be linked with the current one.
$extraColumnsarrayAdditional 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() or ActiveQuery::viaTable().)

Returns

mixed

Throws

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

ParameterTypeDescription
$relationNamesstring|arrayThe names of the relations of this model to be loaded from database. See ActiveQueryInterface::with() on how to specify this argument.
$asArrayboolWhether to load each relation as an array or an object (if the relation itself does not specify that).

Returns

mixed

Since

2.0.50

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

ParameterTypeDescription
$modelsyii\db\TModelsArray 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()).
$relationNamesstring|arrayThe names of the relations of primary models to be loaded from database. See ActiveQueryInterface::with() on how to specify this argument.
$asArrayboolWhether 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

public function markAttributeDirty(string $name): mixed

Marks an attribute dirty.

This method may be called to force updating a record when calling update(), even if there is no change being made to the record.

Parameters

ParameterTypeDescription
$namestringThe attribute name

Returns

mixed

public function offsetExists(mixed $offset): bool

Returns whether there is an element at the specified offset.

This method is required by the interface ArrayAccess.

Parameters

ParameterTypeDescription
$offsetmixedThe offset to check on

Returns

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

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. It is implicitly called when you use something like unset($model[$offset]).

Parameters

ParameterTypeDescription
$offsetmixedThe offset to unset element

Returns

mixed

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 exception will be thrown, and the update or deletion is skipped.

Optimistic locking is only supported by update() and 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 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 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.

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 to populate the query results into active records.

When calling this method manually you should call afterFind() on the created record to trigger the afterFind Event.

Parameters

ParameterTypeDescription
$recordBaseActiveRecordThe record to be populated. In most cases this will be an instance created by instantiate() beforehand.
$rowarrayAttribute values (name => value)

Returns

mixed

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

ParameterTypeDescription
$namestringThe relation name, e.g. orders for a relation defined via getOrders() method (case-sensitive).
$recordsActiveRecordInterface|array|nullThe related records to be populated into the relation.

Returns

mixed

See also

public function refresh(): bool

Repopulates this active record with the latest data.

If the refresh is successful, an 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.

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

Saves the current record.

This method will call insert() when $isNewRecord is true, or update() when $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

ParameterTypeDescription
$runValidationboolWhether to perform validation (calling 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.
$attributeNamesarray|nullList 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: in case update or insert failed.
public function setAttribute(string $name, mixed $value): mixed

Sets the named attribute value.

Parameters

ParameterTypeDescription
$namestringThe attribute name
$valuemixedThe attribute value.

Returns

mixed

Throws

See also

public function setIsNewRecord(bool $value): mixed

Sets the value indicating whether the record is new.

Parameters

ParameterTypeDescription
$valueboolWhether the record is new and should be inserted when calling save().

Returns

mixed

See also

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

Sets the old value of the named attribute.

Parameters

ParameterTypeDescription
$namestringThe attribute name
$valuemixedThe old attribute value.

Returns

mixed

Throws

See also

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

Sets the old attribute values.

All existing old attribute values will be discarded.

Parameters

ParameterTypeDescription
$valuesarray|nullOld attribute values to be set. If set to null this record is considered to be new.

Returns

mixed

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

ParameterTypeDescription
$namestringThe case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method.
$modelActiveRecordInterfaceThe 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.
$deleteboolWhether 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

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

ParameterTypeDescription
$namestringThe case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method.
$deleteboolWhether to delete the model that contains the foreign key. Note that the deletion will be performed using deleteAll(), which will not trigger any events on the related models. If you need EVENT_BEFORE_DELETE or EVENT_AFTER_DELETE to be triggered, you need to find the models first and then call delete() on each of them.

Returns

mixed

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() when $runValidation is true. If beforeValidate() returns false, the rest of the steps will be skipped;
  2. call afterValidate() when $runValidation is true. If validation failed, the rest of the steps will be skipped;
  3. call beforeSave(). If 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();

In the above step 1, 2, 3 and 5, events EVENT_BEFORE_VALIDATE, EVENT_AFTER_VALIDATE, EVENT_BEFORE_UPDATE, and EVENT_AFTER_UPDATE will be raised by the corresponding methods.

Only the changed attribute values 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

ParameterTypeDescription
$runValidationboolWhether to perform validation (calling 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.
$attributeNamesarray|nullList 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() stops the updating process.

Throws

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

ParameterTypeDescription
$attributesarrayAttribute values (name-value pairs) to be saved into the table
$conditionstring|arrayThe conditions that will be put in the WHERE part of the UPDATE SQL. Please refer to Query::where() on how to specify this parameter.

Returns

int: The number of rows updated

Throws

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

ParameterTypeDescription
$countersarrayThe counters to be updated (attribute name => increment value). Use negative values if you want to decrement the counters.
$conditionstring|arrayThe conditions that will be put in the WHERE part of the UPDATE SQL. Please refer to Query::where() on how to specify this parameter.

Returns

int: The number of rows updated

Throws

public function updateAttributes(array $attributes): int

Updates the specified attributes.

This method is a shortcut to 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

ParameterTypeDescription
$attributesarrayThe attributes (names or name-value pairs) to be updated

Returns

int: The number of rows affected.

public function updateCounters(array $counters): bool

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

Note that this method differs from 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

ParameterTypeDescription
$countersarrayThe 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

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

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

Parameters

ParameterTypeDescription
$classstringThe class name of the related record.
$linkarrayThe primary-foreign key constraint.
$multipleboolWhether this query represents a relation to more than one record.

Returns

ActiveQueryInterface: The relational query object.

Since

2.0.12

See also

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

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

Parameters

ParameterTypeDescription
$recordBaseActiveRecordThe record to take attributes from.

Returns

bool: Whether refresh was successful.

Since

2.0.13

See also

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

Parameters

ParameterTypeDescription
$attributesarray|nullAttributes to update

Returns

int|false: The number of rows affected, or false if beforeSave() stops the updating process.

Throws

See also