Abstract Class yii\db\BaseActiveRecord

Inheritanceyii\db\BaseActiveRecord » yii\base\Model » yii\base\Component » yii\base\Object
ImplementsArrayAccess, IteratorAggregate, yii\base\Arrayable, yii\base\Configurable, yii\db\ActiveRecordInterface
Uses Traitsyii\base\ArrayableTrait
Subclassesyii\db\ActiveRecord, yii\elasticsearch\ActiveRecord, yii\mongodb\ActiveRecord, yii\mongodb\file\ActiveRecord, yii\redis\ActiveRecord, yii\sphinx\ActiveRecord
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/db/BaseActiveRecord.php

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

See yii\db\ActiveRecord for a concrete implementation.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$activeValidators yii\validators\Validator[] The validators applicable to the current $scenario. yii\base\Model
$attributes array Attribute values (name => value). yii\base\Model
$behaviors yii\base\Behavior[] List of behaviors attached to this component yii\base\Component
$dirtyAttributes array The changed attribute values (name-value pairs) yii\db\BaseActiveRecord
$errors array Errors for all attributes or the specified attribute. yii\base\Model
$firstErrors array The first errors. yii\base\Model
$isNewRecord boolean Whether the record is new and should be inserted when calling save(). yii\db\BaseActiveRecord
$iterator ArrayIterator An iterator for traversing the items in the list. yii\base\Model
$oldAttributes array The old attribute values (name-value pairs) yii\db\BaseActiveRecord
$oldPrimaryKey mixed The old primary key value. yii\db\BaseActiveRecord
$primaryKey mixed The primary key value. yii\db\BaseActiveRecord
$relatedRecords array An array of related records indexed by relation names. yii\db\BaseActiveRecord
$scenario string The scenario that this model is in. yii\base\Model
$validators ArrayObject|yii\validators\Validator[] All the validators declared in the model. yii\base\Model

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Object
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\Object
__get() PHP getter magic method. yii\db\BaseActiveRecord
__isset() Checks if a property value is null. yii\db\BaseActiveRecord
__set() PHP setter magic method. yii\db\BaseActiveRecord
__unset() Sets a component property to be null. yii\db\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. yii\db\BaseActiveRecord
afterFind() This method is called when the AR object is created and populated with the query result. yii\db\BaseActiveRecord
afterRefresh() This method is called when the AR object is refreshed. yii\db\BaseActiveRecord
afterSave() This method is called at the end of inserting or updating a record. yii\db\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 all attribute names of the record. yii\db\ActiveRecordInterface
beforeDelete() This method is invoked before deleting a record. yii\db\BaseActiveRecord
beforeSave() This method is called at the beginning of inserting or updating a record. yii\db\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. yii\db\BaseActiveRecord
canSetProperty() Returns a value indicating whether a property can be set. yii\db\BaseActiveRecord
className() Returns the fully qualified name of this class. yii\base\Object
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. yii\db\BaseActiveRecord
deleteAll() Deletes rows in the table using the provided conditions. yii\db\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. yii\db\BaseActiveRecord
extraFields() Returns the list of fields that can be expanded further and returned by toArray(). yii\db\BaseActiveRecord
fields() Returns the list of fields that should be returned by default by toArray() when no specific fields are specified. yii\db\BaseActiveRecord
find() Creates an yii\db\ActiveQueryInterface instance for query purpose. yii\db\ActiveRecordInterface
findAll() Returns a list of active record models that match the specified primary key value(s) or a set of column values. yii\db\BaseActiveRecord
findOne() Returns a single active record model instance by a primary key or an array of column values. yii\db\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. yii\db\BaseActiveRecord
getAttributeHint() Returns the text hint for the specified attribute. yii\db\BaseActiveRecord
getAttributeLabel() Returns the text label for the specified attribute. yii\db\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() Returns the connection used by this AR class. yii\db\ActiveRecordInterface
getDirtyAttributes() Returns the attribute values that have been modified since they are loaded or saved most recently. yii\db\BaseActiveRecord
getErrors() Returns the errors for all attributes or a single attribute. 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. yii\db\BaseActiveRecord
getIterator() Returns an iterator for traversing the attributes in the model. yii\base\Model
getOldAttribute() Returns the old value of the named attribute. yii\db\BaseActiveRecord
getOldAttributes() Returns the old attribute values. yii\db\BaseActiveRecord
getOldPrimaryKey() Returns the old primary key value(s). yii\db\BaseActiveRecord
getPrimaryKey() Returns the primary key value(s). yii\db\BaseActiveRecord
getRelatedRecords() Returns all populated related records. yii\db\BaseActiveRecord
getRelation() Returns the relation object with the specified name. yii\db\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. yii\db\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. yii\db\BaseActiveRecord
hasMethod() Returns a value indicating whether a method is defined. yii\base\Object
hasOne() Declares a has-one relation. yii\db\BaseActiveRecord
hasProperty() Returns a value indicating whether a property is defined. yii\base\Object
init() Initializes the object. yii\db\BaseActiveRecord
insert() Inserts the record into the database using the attribute values of this record. yii\db\ActiveRecordInterface
instantiate() Creates an active record instance. yii\db\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. yii\db\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() Returns a value indicating whether the given set of attributes represents the primary key for this model yii\db\BaseActiveRecord
isRelationPopulated() Check whether the named relation has been populated with records. yii\db\BaseActiveRecord
link() Establishes the relationship between two models. yii\db\BaseActiveRecord
load() Populates the model with input data. yii\base\Model
loadMultiple() Populates a set of models with the data from end user. yii\base\Model
markAttributeDirty() Marks an attribute dirty. yii\db\BaseActiveRecord
off() Detaches an existing event handler from this component. yii\base\Component
offsetExists() Returns whether there is an element at the specified offset. yii\db\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. yii\db\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. yii\db\BaseActiveRecord
populateRecord() Populates an active record object using a row of data from the database/storage. yii\db\BaseActiveRecord
populateRelation() Populates the named relation with the related records. yii\db\BaseActiveRecord
primaryKey() Returns the primary key name(s) for this AR class. yii\db\ActiveRecordInterface
refresh() Repopulates this active record with the latest data. yii\db\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. yii\db\BaseActiveRecord
scenarios() Returns a list of scenarios and the corresponding active attributes. yii\base\Model
setAttribute() Sets the named attribute value. yii\db\BaseActiveRecord
setAttributes() Sets the attribute values in a massive way. yii\base\Model
setIsNewRecord() Sets the value indicating whether the record is new. yii\db\BaseActiveRecord
setOldAttribute() Sets the old value of the named attribute. yii\db\BaseActiveRecord
setOldAttributes() Sets the old attribute values. yii\db\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. yii\db\BaseActiveRecord
unlinkAll() Destroys the relationship in current model. yii\db\BaseActiveRecord
update() Saves the changes to this active record into the associated database table. yii\db\BaseActiveRecord
updateAll() Updates the whole table using the provided attribute values and conditions. yii\db\BaseActiveRecord
updateAllCounters() Updates the whole table using the provided counter changes and conditions. yii\db\BaseActiveRecord
updateAttributes() Updates the specified attributes. yii\db\BaseActiveRecord
updateCounters() Updates one or several counter columns for the current AR object. yii\db\BaseActiveRecord
validate() Performs the data validation. yii\base\Model
validateMultiple() Validates multiple models. yii\base\Model

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
findByCondition() Finds ActiveRecord instance(s) by the given condition. yii\db\BaseActiveRecord
resolveFields() Determines which fields can be returned by toArray(). yii\base\ArrayableTrait
updateInternal() yii\db\BaseActiveRecord

Events

Hide inherited events

EventTypeDescriptionDefined By
EVENT_AFTER_DELETE yii\base\Event An event that is triggered after a record is deleted. yii\db\BaseActiveRecord
EVENT_AFTER_FIND yii\base\Event An event that is triggered after the record is created and populated with query result. yii\db\BaseActiveRecord
EVENT_AFTER_INSERT yii\db\AfterSaveEvent An event that is triggered after a record is inserted. yii\db\BaseActiveRecord
EVENT_AFTER_REFRESH yii\base\Event An event that is triggered after a record is refreshed. (available since version 2.0.8) yii\db\BaseActiveRecord
EVENT_AFTER_UPDATE yii\db\AfterSaveEvent An event that is triggered after a record is updated. yii\db\BaseActiveRecord
EVENT_AFTER_VALIDATE yii\base\Event An event raised at the end of validate() yii\base\Model
EVENT_BEFORE_DELETE yii\base\ModelEvent An event that is triggered before deleting a record. yii\db\BaseActiveRecord
EVENT_BEFORE_INSERT yii\base\ModelEvent An event that is triggered before inserting a record. yii\db\BaseActiveRecord
EVENT_BEFORE_UPDATE yii\base\ModelEvent An event that is triggered before updating a record. yii\db\BaseActiveRecord
EVENT_BEFORE_VALIDATE yii\base\ModelEvent An event raised at the beginning of validate(). yii\base\Model
EVENT_INIT yii\base\Event An event that is triggered when the record is initialized via init(). yii\db\BaseActiveRecord

Constants

Hide inherited constants

ConstantValueDescriptionDefined By
SCENARIO_DEFAULT 'default' The name of the default scenario. yii\base\Model

Property Details

$dirtyAttributes public read-only property

The changed attribute values (name-value pairs)

public array getDirtyAttributes ( $names null )
$isNewRecord public property

Whether the record is new and should be inserted when calling save().

public boolean getIsNewRecord ( )
public void setIsNewRecord ( $value )
$oldAttributes public property

The old attribute values (name-value pairs)

public array getOldAttributes ( )
public void setOldAttributes ( $values )
$oldPrimaryKey public read-only property

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

public mixed getOldPrimaryKey ( $asArray false )
$primaryKey public read-only property

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 mixed getPrimaryKey ( $asArray false )
$relatedRecords public read-only property

An array of related records indexed by relation names.

Method Details

__get() public method

PHP getter magic method.

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

See also getAttribute().

public mixed __get ( $name )
$name string

Property name

return mixed

Property value

throws yii\base\InvalidParamException

if relation name is wrong

__isset() public method

Checks if a property value is null.

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

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the property value is null

__set() public method

PHP setter magic method.

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

public void __set ( $name, $value )
$name string

Property name

$value mixed

Property value

__unset() public method

Sets a component property to be null.

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

public void __unset ( $name )
$name string

The property name or the event name

afterDelete() public method

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.

public void afterDelete ( )
afterFind() public method

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.

public void afterFind ( )
afterRefresh() public method (available since version 2.0.8)

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.

public void afterRefresh ( )
afterSave() public method

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 yii\db\AfterSaveEvent. When overriding this method, make sure you call the parent implementation so that the event is triggered.

public void afterSave ( $insert, $changedAttributes )
$insert boolean

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 yii\behaviors\AttributeTypecastBehavior to facilitate attribute typecasting. See http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting.

beforeDelete() public method

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()) {
        // ...custom code here...
        return true;
    } else {
        return false;
    }
}
public boolean beforeDelete ( )
return boolean

Whether the record should be deleted. Defaults to true.

beforeSave() public method

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)) {
        // ...custom code here...
        return true;
    } else {
        return false;
    }
}
public boolean beforeSave ( $insert )
$insert boolean

Whether this method called while inserting a record. If false, it means the method is called while updating a record.

return boolean

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

canGetProperty() public method

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).
public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be read

canSetProperty() public method

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).
public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be written

delete() public method

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.

public integer|false delete ( )
return integer|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 yii\db\StaleObjectException

if optimistic locking is enabled and the data being deleted is outdated.

throws yii\db\Exception

in case delete failed.

deleteAll() public static method

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');
public static integer deleteAll ( $condition null )
$condition string|array

The conditions that will be put in the WHERE part of the DELETE SQL. Please refer to yii\db\Query::where() on how to specify this parameter.

return integer

The number of rows deleted

throws yii\base\NotSupportedException

if not overridden.

equals() public method

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.

public boolean equals ( $record )
$record yii\db\ActiveRecordInterface

Record to compare to

return boolean

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

extraFields() public method

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

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

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

public array extraFields ( )
return array

The list of expandable field names or field definitions. Please refer to fields() on the format of the return value.

fields() public method

Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.

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.

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

public array fields ( )
return array

The list of field names or field definitions.

findAll() public static method

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.

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();
public static static[] findAll ( $condition )
$condition mixed

Primary key value or a set of column values

return static[]

An array of ActiveRecord instances, or an empty array if nothing matches.

findByCondition() protected static method

Finds ActiveRecord instance(s) by the given condition.

This method is internally called by findOne() and findAll().

protected static yii\db\ActiveQueryInterface findByCondition ( $condition )
$condition mixed

Please refer to findOne() for the explanation of this parameter

return yii\db\ActiveQueryInterface

The newly created ActiveQuery instance.

throws yii\base\InvalidConfigException

if there is no primary key defined

findOne() public static method

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.

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();
public static static findOne ( $condition )
$condition mixed

Primary key value or a set of column values

return static

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

getAttribute() public method

Returns the named attribute value.

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

See also hasAttribute().

public mixed getAttribute ( $name )
$name string

The attribute name

return mixed

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

getAttributeHint() public method (available since version 2.0.4)

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.

See also attributeHints().

public string getAttributeHint ( $attribute )
$attribute string

The attribute name

return string

The attribute hint

getAttributeLabel() public method

Returns the text label for the specified attribute.

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

See also:

public string getAttributeLabel ( $attribute )
$attribute string

The attribute name

return string

The attribute label

getDirtyAttributes() public method

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

public array getDirtyAttributes ( $names null )
$names string[]|null

The names of the attributes whose values may be returned if they are changed recently. If null, attributes() will be used.

return array

The changed attribute values (name-value pairs)

getIsNewRecord() public method

Returns a value indicating whether the current record is new.

public boolean getIsNewRecord ( )
return boolean

Whether the record is new and should be inserted when calling save().

getOldAttribute() public method

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.

See also hasAttribute().

public mixed getOldAttribute ( $name )
$name string

The attribute name

return mixed

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

getOldAttributes() public method

Returns the old attribute values.

public array getOldAttributes ( )
return array

The old attribute values (name-value pairs)

getOldPrimaryKey() public method

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.

public mixed getOldPrimaryKey ( $asArray false )
$asArray boolean

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.

return 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 yii\db\Exception

if the AR model does not have a primary key

getPrimaryKey() public method

Returns the primary key value(s).

public mixed getPrimaryKey ( $asArray false )
$asArray boolean

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.

return 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() public method

Returns all populated related records.

See also getRelation().

public array getRelatedRecords ( )
return array

An array of related records indexed by relation names.

getRelation() public method

Returns the relation object with the specified name.

A relation is defined by a getter method which returns an yii\db\ActiveQueryInterface object. It can be declared in either the Active Record class itself or one of its behaviors.

public yii\db\ActiveQueryInterface|yii\db\ActiveQuery getRelation ( $name, $throwException true )
$name string

The relation name, e.g. orders for a relation defined via getOrders() method (case-sensitive).

$throwException boolean

Whether to throw exception if the relation does not exist.

return yii\db\ActiveQueryInterface|yii\db\ActiveQuery

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

throws yii\base\InvalidParamException

if the named relation does not exist.

hasAttribute() public method

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

public boolean hasAttribute ( $name )
$name string

The name of the attribute

return boolean

Whether the model has an attribute with the specified name.

hasMany() public method

Declares a has-many relation.

The declaration is returned in terms of a relational yii\db\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::className(), ['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 yii\db\ActiveQuery to further customize the relation.

public yii\db\ActiveQueryInterface hasMany ( $class, $link )
$class string

The class name of the related record

$link array

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.

return yii\db\ActiveQueryInterface

The relational query object.

hasOne() public method

Declares a has-one relation.

The declaration is returned in terms of a relational yii\db\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::className(), ['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 yii\db\ActiveQuery to further customize the relation.

public yii\db\ActiveQueryInterface hasOne ( $class, $link )
$class string

The class name of the related record

$link array

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.

return yii\db\ActiveQueryInterface

The relational query object.

init() public method

Initializes the object.

This method is called at the end of the constructor. The default implementation will trigger an EVENT_INIT event. If you override this method, make sure you call the parent implementation at the end to ensure triggering of the event.

public void init ( )
instantiate() public static method

Creates an active record instance.

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

public static static instantiate ( $row )
$row array

Row data to be populated into the record.

return static

The newly created active record

isAttributeChanged() public method

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

public boolean isAttributeChanged ( $name, $identical true )
$name string

The name of the attribute.

$identical boolean

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.

return boolean

Whether the attribute has been changed

isPrimaryKey() public static method

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

public static boolean isPrimaryKey ( $keys )
$keys array

The set of attributes to check

return boolean

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

isRelationPopulated() public method

Check whether the named relation has been populated with records.

See also getRelation().

public boolean isRelationPopulated ( $name )
$name string

The relation name, e.g. orders for a relation defined via getOrders() method (case-sensitive).

return boolean

Whether relation has been populated with records.

link() public method

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.

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.

public void link ( $name, $model, $extraColumns = [] )
$name string

The case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method.

$model yii\db\ActiveRecordInterface

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 yii\db\ActiveRelationTrait::via() or yii\db\ActiveQuery::viaTable().)

throws yii\base\InvalidCallException

if the method is unable to link two models.

markAttributeDirty() public method

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.

public void markAttributeDirty ( $name )
$name string

The attribute name

offsetExists() public method

Returns whether there is an element at the specified offset.

This method is required by the interface ArrayAccess.

public boolean offsetExists ( $offset )
$offset mixed

The offset to check on

return boolean

Whether there is an element at the specified offset.

offsetUnset() public method

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

public void offsetUnset ( $offset )
$offset mixed

The offset to unset element

optimisticLock() public method

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 yii\db\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. Add a required validation rule for the version column to ensure the version value is submitted.
  3. In the Web form that collects the user input, add a hidden field that stores the lock version of the recording being updated.
  4. In the controller action that does the data updating, try to catch the yii\db\StaleObjectException and implement necessary business logic (e.g. merging the changes, prompting stated data) to resolve the conflict.
public string optimisticLock ( )
return string

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() public static method

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 yii\db\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.

public static void populateRecord ( $record, $row )
$record yii\db\BaseActiveRecord

The record to be populated. In most cases this will be an instance created by instantiate() beforehand.

$row array

Attribute values (name => value)

populateRelation() public method

Populates the named relation with the related records.

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

See also getRelation().

public void populateRelation ( $name, $records )
$name string

The relation name, e.g. orders for a relation defined via getOrders() method (case-sensitive).

$records yii\db\ActiveRecordInterface|array|null

The related records to be populated into the relation.

refresh() public method

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.

public boolean refresh ( )
return boolean

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

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();
public boolean save ( $runValidation true, $attributeNames null )
$runValidation boolean

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

$attributeNames array

List of attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved.

return boolean

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

setAttribute() public method

Sets the named attribute value.

See also hasAttribute().

public void setAttribute ( $name, $value )
$name string

The attribute name

$value mixed

The attribute value.

throws yii\base\InvalidParamException

if the named attribute does not exist.

setIsNewRecord() public method

Sets the value indicating whether the record is new.

See also getIsNewRecord().

public void setIsNewRecord ( $value )
$value boolean

Whether the record is new and should be inserted when calling save().

setOldAttribute() public method

Sets the old value of the named attribute.

See also hasAttribute().

public void setOldAttribute ( $name, $value )
$name string

The attribute name

$value mixed

The old attribute value.

throws yii\base\InvalidParamException

if the named attribute does not exist.

setOldAttributes() public method

Sets the old attribute values.

All existing old attribute values will be discarded.

public void setOldAttributes ( $values )
$values array|null

Old attribute values to be set. If set to null this record is considered to be new.

unlink() public method

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.

public void unlink ( $name, $model, $delete false )
$name string

The case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method.

$model yii\db\ActiveRecordInterface

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 boolean

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.

throws yii\base\InvalidCallException

if the models cannot be unlinked

unlinkAll() public method

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

public void unlinkAll ( $name, $delete false )
$name string

The case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method.

$delete boolean

Whether to delete the model that contains the foreign key.

update() public method

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
}
public integer|false update ( $runValidation true, $attributeNames null )
$runValidation boolean

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

$attributeNames array

List of attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved.

return integer|false

The number of rows affected, or false if validation fails or beforeSave() stops the updating process.

throws yii\db\StaleObjectException

if optimistic locking is enabled and the data being updated is outdated.

throws yii\db\Exception

in case update failed.

updateAll() public static method

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');
public static integer updateAll ( $attributes, $condition '' )
$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 yii\db\Query::where() on how to specify this parameter.

return integer

The number of rows updated

throws yii\base\NotSupportedException

if not overridden

updateAllCounters() public static method

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

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

Customer::updateAllCounters(['age' => 1]);
public static integer updateAllCounters ( $counters, $condition '' )
$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 yii\db\Query::where() on how to specify this parameter.

return integer

The number of rows updated

throws yii\base\NotSupportedException

if not overrided

updateAttributes() public method

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.

public integer updateAttributes ( $attributes )
$attributes array

The attributes (names or name-value pairs) to be updated

return integer

The number of rows affected.

updateCounters() public method

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]);

See also updateAllCounters().

public boolean updateCounters ( $counters )
$counters array

The counters to be updated (attribute name => increment value) Use negative values if you want to decrement the counters.

return boolean

Whether the saving is successful

updateInternal() protected method

See also update().

protected integer|false updateInternal ( $attributes null )
$attributes array

Attributes to update

return integer|false

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

throws yii\db\StaleObjectException

Event Details

EVENT_AFTER_DELETE event of type yii\base\Event

An event that is triggered after a record is deleted.

EVENT_AFTER_FIND event of type yii\base\Event

An event that is triggered after the record is created and populated with query result.

EVENT_AFTER_INSERT event of type yii\db\AfterSaveEvent

An event that is triggered after a record is inserted.

EVENT_AFTER_REFRESH event of type yii\base\Event (available since version 2.0.8)

An event that is triggered after a record is refreshed.

EVENT_AFTER_UPDATE event of type yii\db\AfterSaveEvent

An event that is triggered after a record is updated.

EVENT_BEFORE_DELETE event of type yii\base\ModelEvent

An event that is triggered before deleting a record. You may set yii\base\ModelEvent::$isValid to be false to stop the deletion.

EVENT_BEFORE_INSERT event of type yii\base\ModelEvent

An event that is triggered before inserting a record. You may set yii\base\ModelEvent::$isValid to be false to stop the insertion.

EVENT_BEFORE_UPDATE event of type yii\base\ModelEvent

An event that is triggered before updating a record. You may set yii\base\ModelEvent::$isValid to be false to stop the update.

EVENT_INIT event of type yii\base\Event

An event that is triggered when the record is initialized via init().