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.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$activeValidators read-only | yii\[] | The validators applicable to the current $scenario. | yii\ |
$attributes | array<string, | Attribute values (name => value). | yii\ |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$dirtyAttributes read-only | array | The changed attribute values (name-value pairs). | BaseActiveRecord |
$errors read-only | array<string, | Errors for all attributes. | yii\ |
$firstErrors read-only | array<string, | The first errors. | yii\ |
$isNewRecord | bool | Whether the record is new and should be inserted when calling save(). | BaseActiveRecord |
$iterator read-only | ArrayIterator<string, | An iterator for traversing the items in the list. | yii\ |
$oldAttributes | array| | Old attribute values to be set. | BaseActiveRecord |
$oldPrimaryKey read-only | mixed | The old primary key value. | BaseActiveRecord |
$primaryKey read-only | mixed | The primary key value. | BaseActiveRecord |
$relatedRecords read-only | array | An array of related records indexed by relation names. | BaseActiveRecord |
$scenario | string | The scenario that this model is in. | yii\ |
$validators read-only | ArrayObject<int, yii\>|yii\[] | All the validators declared in the model. | yii\ |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__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\ |
addError() | Adds a new error to the specified attribute. | yii\ |
addErrors() | Adds a list of errors. | yii\ |
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\ |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
attributeHints() | Returns the attribute hints. | yii\ |
attributeLabels() | Returns the attribute labels. | yii\ |
attributes() | Returns the list of attribute names. | yii\ |
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\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
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() static | Returns the fully qualified name of this class. | yii\ |
clearErrors() | Removes errors for all attributes or a single attribute. | yii\ |
createValidators() | Creates validator objects based on the validation rules specified in rules(). | yii\ |
delete() | Deletes the table row corresponding to this active record. | BaseActiveRecord |
deleteAll() static | Deletes rows in the table using the provided conditions. | BaseActiveRecord |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
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 abstract | Creates an ActiveQueryInterface instance for query purpose. | ActiveRecordInterface |
findAll() static | Returns a list of active record models that match the specified primary key value(s) or a set of column values. | BaseActiveRecord |
findOne() static | Returns 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\ |
generateAttributeLabel() | Generates a user friendly attribute label based on the give attribute name. | yii\ |
getActiveValidators() | Returns the validators applicable to the current $scenario. | yii\ |
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\ |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getDb() static abstract | Returns 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\ |
getErrorSummary() | Returns the errors for all attributes as a one-dimensional array. | yii\ |
getFirstError() | Returns the first error of the specified attribute. | yii\ |
getFirstErrors() | Returns the first error of every attribute in the model. | yii\ |
getIsNewRecord() | Returns a value indicating whether the current record is new. | BaseActiveRecord |
getIterator() | Returns an iterator for traversing the attributes in the model. | yii\ |
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\ |
getValidators() | Returns all the validators declared in rules(). | yii\ |
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\ |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMany() | Declares a has-many relation. | BaseActiveRecord |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasOne() | Declares a has-one relation. | BaseActiveRecord |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the object. | BaseActiveRecord |
insert() abstract | Inserts the record into the database using the attribute values of this record. | ActiveRecordInterface |
instance() static | Returns static class instance, which can be used to obtain meta information. | yii\ |
instantiate() static | Creates an active record instance. | BaseActiveRecord |
isAttributeActive() | Returns a value indicating whether the attribute is active in the current scenario. | yii\ |
isAttributeChanged() | Returns a value indicating whether the named attribute has been changed. | BaseActiveRecord |
isAttributeRequired() | Returns a value indicating whether the attribute is required. | yii\ |
isAttributeSafe() | Returns a value indicating whether the attribute is safe for massive assignments. | yii\ |
isPrimaryKey() static | Returns 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\ |
loadMultiple() static | Populates a set of models with the data from end user. | yii\ |
loadRelations() | Eager loads related models for the already loaded primary model. | BaseActiveRecord |
loadRelationsFor() static | Eager 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\ |
offsetExists() | Returns whether there is an element at the specified offset. | BaseActiveRecord |
offsetGet() | Returns the element at the specified offset. | yii\ |
offsetSet() | Sets the element at the specified offset. | yii\ |
offsetUnset() | Sets the element value at the specified offset to null. | BaseActiveRecord |
on() | Attaches an event handler to an event. | yii\ |
onUnsafeAttribute() | This method is invoked when an unsafe attribute is being massively assigned. | yii\ |
optimisticLock() | Returns the name of the column that stores the lock version for implementing optimistic locking. | BaseActiveRecord |
populateRecord() static | Populates 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 abstract | Returns 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\ |
safeAttributes() | Returns the attribute names that are safe to be massively assigned in the current scenario. | yii\ |
save() | Saves the current record. | BaseActiveRecord |
scenarios() | Returns a list of scenarios and the corresponding active attributes. | yii\ |
setAttribute() | Sets the named attribute value. | BaseActiveRecord |
setAttributes() | Sets the attribute values in a massive way. | yii\ |
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\ |
toArray() | Converts the model into an array. | yii\ |
trigger() | Triggers an event. | yii\ |
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() static | Updates the whole table using the provided attribute values and conditions. | BaseActiveRecord |
updateAllCounters() static | Updates 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\ |
validateMultiple() static | Validates multiple models. | yii\ |
createRelationQuery() protected | Creates a query instance for has-one or has-many relation. | BaseActiveRecord |
extractFieldsFor() protected | Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: “item.id” The previous example would extract “id”. | yii\ |
extractRootFields() protected | Extracts the root field names from nested fields. | yii\ |
refreshInternal() protected | Repopulates this active record with the latest data from a newly fetched instance. | BaseActiveRecord |
resolveFields() protected | Determines which fields can be returned by toArray(). | yii\ |
updateInternal() protected | BaseActiveRecord |
Events
Section titled “Events”| Event | Type | Description | Defined by |
|---|---|---|---|
EVENT_INIT | yii\ | An event that is triggered when the record is initialized via init(). Event name: 'init'. | BaseActiveRecord |
EVENT_AFTER_FIND | yii\ | An event that is triggered after the record is created and populated with query result. Event name: 'afterFind'. | BaseActiveRecord |
EVENT_BEFORE_INSERT | yii\ | An event that is triggered before inserting a record. Event name: 'beforeInsert'. | BaseActiveRecord |
EVENT_AFTER_INSERT | AfterSaveEvent | An event that is triggered after a record is inserted. Event name: 'afterInsert'. | BaseActiveRecord |
EVENT_BEFORE_UPDATE | yii\ | An event that is triggered before updating a record. Event name: 'beforeUpdate'. | BaseActiveRecord |
EVENT_AFTER_UPDATE | AfterSaveEvent | An event that is triggered after a record is updated. Event name: 'afterUpdate'. | BaseActiveRecord |
EVENT_BEFORE_DELETE | yii\ | An event that is triggered before deleting a record. Event name: 'beforeDelete'. | BaseActiveRecord |
EVENT_AFTER_DELETE | yii\ | An event that is triggered after a record is deleted. Event name: 'afterDelete'. | BaseActiveRecord |
EVENT_AFTER_REFRESH | yii\ | An event that is triggered after a record is refreshed. Event name: 'afterRefresh'. Available since 2.0.8. | BaseActiveRecord |
EVENT_BEFORE_VALIDATE | yii\ | An event raised at the beginning of validate(). Event name: 'beforeValidate'. | yii\ |
EVENT_AFTER_VALIDATE | yii\ | An event raised at the end of validate() Event name: 'afterValidate'. | yii\ |
Constants
Section titled “Constants”| Constant | Value | Description | Defined by |
|---|---|---|---|
SCENARIO_DEFAULT | 'default' | The name of the default scenario. | yii\ |
Property details
Section titled “Property details”$oldAttributes
Section titled “$oldAttributes ”public array|null $oldAttributesOld attribute values to be set.
If set to null this record is
considered to be new.
$oldPrimaryKey
Section titled “$oldPrimaryKey ”public mixed $oldPrimaryKeyThe old primary key value.
An array (column name => column value) is
returned if the primary key is composite or $asArray is true. A string is returned otherwise (null will be
returned if the key value is null).
Access
Read-only (virtual property).
$primaryKey
Section titled “$primaryKey ”public mixed $primaryKeyThe primary key value.
An array (column name => column value) is returned
if the primary key is composite or $asArray is true. A string is returned otherwise (null will be returned
if the key value is null).
Access
Read-only (virtual property).
Method details
Section titled “Method details”__get()
Section titled “__get() ”public function __get(string $name): mixedPHP getter magic method.
This method is overridden so that attributes and related objects can be accessed like properties.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | Property name |
Returns
mixed: Property value
Throws
yii\base\InvalidArgumentException: if relation name is wrong
See also
__isset()
Section titled “__isset() ”public function __isset(string $name): boolChecks if a property value is null.
This method overrides the parent implementation by checking if the named attribute is null or not.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The property name or the event name |
Returns
bool: Whether the property value is null
__set()
Section titled “__set() ”public function __set(string $name, mixed $value): mixedPHP setter magic method.
This method is overridden so that AR attributes can be accessed like properties.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | Property name |
$value | mixed | Property value |
Returns
mixed
__unset()
Section titled “__unset() ”public function __unset(string $name): mixedSets a component property to be null.
This method overrides the parent implementation by clearing the specified attribute value.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The property name or the event name |
Returns
mixed
afterDelete()
Section titled “afterDelete() ”public function afterDelete(): mixedThis 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
afterFind()
Section titled “afterFind() ”public function afterFind(): mixedThis 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
afterRefresh()
Section titled “afterRefresh() ”public function afterRefresh(): mixedThis 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
afterSave()
Section titled “afterSave() ”public function afterSave(bool $insert, array $changedAttributes): mixedThis 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
| Parameter | Type | Description |
|---|---|---|
$insert | bool | Whether this method called while inserting a record. If false, it means the method is called while updating a record. |
$changedAttributes | array | The old values of attributes that had changed and were saved. You can use this parameter to take action based on the changes made for example send an email when the password had changed or implement audit trail that tracks all the changes. $changedAttributes gives you the old attribute values while the active record ($this) has already the new, updated values. Note that no automatic type conversion performed by default. You may use AttributeTypecastBehavior to facilitate attribute typecasting. See https://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting. |
Returns
mixed
beforeDelete()
Section titled “beforeDelete() ”public function beforeDelete(): boolThis 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.
beforeSave()
Section titled “beforeSave() ”public function beforeSave(bool $insert): boolThis 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
| Parameter | Type | Description |
|---|---|---|
$insert | bool | Whether this method called while inserting a record. If false, it means the method is called while updating a record. |
Returns
bool: Whether the insertion or updating should continue. If false, the insertion or updating will be cancelled.
canGetProperty()
Section titled “canGetProperty() ”public function canGetProperty(mixed $name, mixed $checkVars = true, mixed $checkBehaviors = true): boolReturns 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
$checkVarsis true); - an attached behavior has a readable property of the given name (when
$checkBehaviorsis true).
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | mixed | The property name |
$checkVars | mixed | Whether to treat member variables as properties |
$checkBehaviors | mixed | Whether to treat behaviors’ properties as properties of this component |
Returns
bool: Whether the property can be read
canSetOldAttribute()
Section titled “canSetOldAttribute() ”public function canSetOldAttribute(string $name): boolReturns if the old named attribute can be set.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The attribute name |
Returns
bool: Whether the old attribute can be set
See also
canSetProperty()
Section titled “canSetProperty() ”public function canSetProperty(mixed $name, mixed $checkVars = true, mixed $checkBehaviors = true): boolReturns 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
$checkVarsis true); - an attached behavior has a writable property of the given name (when
$checkBehaviorsis true).
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | mixed | The property name |
$checkVars | mixed | Whether to treat member variables as properties |
$checkBehaviors | mixed | Whether to treat behaviors’ properties as properties of this component |
Returns
bool: Whether the property can be written
delete()
Section titled “delete() ”public function delete(): int|falseDeletes the table row corresponding to this active record.
This method performs the following steps in order:
- call
beforeDelete(). If the method returnsfalse, it will skip the rest of the steps; - delete the record from the database;
- 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
StaleObjectException: if optimistic locking is enabled and the data being deleted is outdated.Exception: in case delete failed.
deleteAll()
Section titled “deleteAll() ”public static function deleteAll(string|array|null $condition = null): intDeletes rows in the table using the provided conditions.
WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
For example, to delete all customers whose status is 3:
Customer::deleteAll('status = 3');Parameters
| Parameter | Type | Description |
|---|---|---|
$condition | string| | The 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
yii\base\NotSupportedException: if not overridden.
equals()
Section titled “equals() ”public function equals(yii\db\ActiveRecordInterface $record): boolReturns 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
| Parameter | Type | Description |
|---|---|---|
$record | ActiveRecordInterface | Record to compare to |
Returns
bool: Whether the two active records refer to the same row in the same database table.
extraFields()
Section titled “extraFields() ”public function extraFields(): arrayReturns 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.
fields()
Section titled “fields() ”public function fields(): arrayReturns 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 nameemail;firstNameandlastName: the field names arefirstNameandlastName, and their values are obtained from thefirst_nameandlast_nameproperties;fullName: the field name isfullName. Its value is obtained by concatenatingfirst_nameandlast_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.
findAll()
Section titled “findAll() ”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
WHEREcondition. - 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 scalarpublic function actionView($id){ $model = Post::findOne($id); // ...}
// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record$model = Post::findOne(['id' => Yii::$app->request->get('id')]);
// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!$model = Post::findOne(Yii::$app->request->get('id'));Parameters
| Parameter | Type | Description |
|---|---|---|
$condition | mixed | Primary key value or a set of column values |
Returns
static[]: An array of ActiveRecord instances, or an empty array if nothing matches.
findOne()
Section titled “findOne() ”public static function findOne(mixed $condition): static|nullReturns 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
nullif not found). - a non-associative array: query by a list of primary key values and return the
first record (or
nullif 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
nullif 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 scalarpublic function actionView($id){ $model = Post::findOne($id); // ...}
// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record$model = Post::findOne(['id' => Yii::$app->request->get('id')]);
// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!$model = Post::findOne(Yii::$app->request->get('id'));Parameters
| Parameter | Type | Description |
|---|---|---|
$condition | mixed | Primary key value or a set of column values |
Returns
static|null: ActiveRecord instance matching the condition, or null if nothing matches.
getAttribute()
Section titled “getAttribute() ”public function getAttribute(string $name): mixedReturns the named attribute value.
If this record is the result of a query and the attribute is not loaded,
null will be returned.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The attribute name |
Returns
mixed: The attribute value. null if the attribute is not set or does not exist.
See also
getAttributeHint()
Section titled “getAttributeHint() ”public function getAttributeHint(string $attribute): stringReturns the text hint for the specified attribute.
If the attribute looks like relatedModel.attribute, then the attribute will be received from the related model.
Parameters
| Parameter | Type | Description |
|---|---|---|
$attribute | string | The attribute name |
Returns
string: The attribute hint
Since
2.0.4
See also
getAttributeLabel()
Section titled “getAttributeLabel() ”public function getAttributeLabel(string $attribute): stringReturns 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
| Parameter | Type | Description |
|---|---|---|
$attribute | string | The attribute name |
Returns
string: The attribute label
See also
getDirtyAttributes()
Section titled “getDirtyAttributes() ”public function getDirtyAttributes(string[]|null $names = null): arrayReturns the attribute values that have been modified since they are loaded or saved most recently.
The comparison of new and old values is made for identical values using ===.
Parameters
| Parameter | Type | Description |
|---|---|---|
$names | string[]| | The 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)
getIsNewRecord()
Section titled “getIsNewRecord() ”public function getIsNewRecord(): boolReturns a value indicating whether the current record is new.
Returns
bool: Whether the record is new and should be inserted when calling save().
getOldAttribute()
Section titled “getOldAttribute() ”public function getOldAttribute(string $name): mixedReturns the old value of the named attribute.
If this record is the result of a query and the attribute is not loaded,
null will be returned.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The attribute name |
Returns
mixed: The old attribute value. null if the attribute is not loaded before or does not exist.
See also
getOldAttributes()
Section titled “getOldAttributes() ”public function getOldAttributes(): arrayReturns the old attribute values.
Returns
array: The old attribute values (name-value pairs)
getOldPrimaryKey()
Section titled “getOldPrimaryKey() ”public function getOldPrimaryKey(bool $asArray = false): mixedReturns the old primary key value(s).
This refers to the primary key value that is populated into the record after executing a find method (e.g. find(), findOne()). The value remains unchanged even if the primary key attribute is manually assigned with a different value.
Parameters
| Parameter | Type | Description |
|---|---|---|
$asArray | bool | Whether to return the primary key value as an array. If true, the return value will be an array with column name as key and column value as value. If this is false (default), a scalar value will be returned for non-composite primary key. |
Returns
mixed: The old primary key value. An array (column name => column value) is returned if the primary key is composite or $asArray is true. A string is returned otherwise (null will be returned if the key value is null).
Throws
Exception: if the AR model does not have a primary key
getPrimaryKey()
Section titled “getPrimaryKey() ”public function getPrimaryKey(bool $asArray = false): mixedReturns the primary key value(s).
Parameters
| Parameter | Type | Description |
|---|---|---|
$asArray | bool | Whether to return the primary key value as an array. If true, the return value will be an array with column names as keys and column values as values. Note that for composite primary keys, an array will always be returned regardless of this parameter value. |
Returns
mixed: The primary key value. An array (column name => column value) is returned if the primary key is composite or $asArray is true. A string is returned otherwise (null will be returned if the key value is null).
getRelatedRecords()
Section titled “getRelatedRecords() ”public function getRelatedRecords(): arrayReturns all populated related records.
getRelation()
Section titled “getRelation() ”public function getRelation(string $name, bool $throwException = true): yii\db\ActiveQueryInterface|yii\db\ActiveQuery|nullReturns 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
| Parameter | Type | Description |
|---|---|---|
$name | string | The relation name, e.g. orders for a relation defined via getOrders() method (case-sensitive). |
$throwException | bool | Whether to throw exception if the relation does not exist. |
Returns
ActiveQueryInterface|ActiveQuery|null: The relational query object. If the relation does not exist and $throwException is false, null will be returned.
Throws
yii\base\InvalidArgumentException: if the named relation does not exist.
hasAttribute()
Section titled “hasAttribute() ”public function hasAttribute(string $name): boolReturns a value indicating whether the model has an attribute with the specified name.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The name of the attribute |
Returns
bool: Whether the model has an attribute with the specified name.
hasMany()
Section titled “hasMany() ”public function hasMany(class-string $class, array<string, string> $link): yii\db\ActiveQueryInterfaceDeclares 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
| Parameter | Type | Description |
|---|---|---|
$class | class-string | The class name of the related record |
$link | array<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.
hasOne()
Section titled “hasOne() ”public function hasOne(class-string $class, array<string, string> $link): yii\db\ActiveQueryInterfaceDeclares 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
| Parameter | Type | Description |
|---|---|---|
$class | class-string | The class name of the related record |
$link | array<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.
init()
Section titled “init() ”public function init(): mixedInitializes the object.
This method is called at the end of the constructor.
The default implementation will trigger an EVENT_INIT event.
Returns
mixed
instantiate()
Section titled “instantiate() ”public static function instantiate(array $row): staticCreates 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
| Parameter | Type | Description |
|---|---|---|
$row | array | Row data to be populated into the record. |
Returns
static: The newly created active record
isAttributeChanged()
Section titled “isAttributeChanged() ”public function isAttributeChanged(string $name, bool $identical = true): boolReturns a value indicating whether the named attribute has been changed.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The name of the attribute. |
$identical | bool | Whether the comparison of new and old value is made for identical values using ===, defaults to true. Otherwise == is used for comparison. This parameter is available since version 2.0.4. |
Returns
bool: Whether the attribute has been changed
isPrimaryKey()
Section titled “isPrimaryKey() ”public static function isPrimaryKey(array $keys): boolReturns a value indicating whether the given set of attributes represents the primary key for this model.
Parameters
| Parameter | Type | Description |
|---|---|---|
$keys | array | The set of attributes to check |
Returns
bool: Whether the given set of attributes represents the primary key for this model
isRelationPopulated()
Section titled “isRelationPopulated() ”public function isRelationPopulated(string $name): boolCheck whether the named relation has been populated with records.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The relation name, e.g. orders for a relation defined via getOrders() method (case-sensitive). |
Returns
bool: Whether relation has been populated with records.
See also
link()
Section titled “link() ”public function link(string $name, yii\db\ActiveRecordInterface $model, array $extraColumns = []): mixedEstablishes the relationship between two models.
The relationship is established by setting the foreign key value(s) in one model to be the corresponding primary key value(s) in the other model. The model with the foreign key will be saved into database without performing validation and without events/behaviors.
If the relationship involves a junction table, a new row will be inserted into the junction table which contains the primary key values from both models.
Note that this method requires that the primary key value is not null.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method. |
$model | ActiveRecordInterface | The model to be linked with the current one. |
$extraColumns | array | Additional column values to be saved into the junction table. This parameter is only meaningful for a relationship involving a junction table (i.e., a relation set with ActiveRelationTrait::via() or ActiveQuery::viaTable().) |
Returns
mixed
Throws
yii\base\InvalidCallException: if the method is unable to link two models.
loadRelations()
Section titled “loadRelations() ”public function loadRelations(string|array $relationNames, bool $asArray = false): mixedEager loads related models for the already loaded primary model.
Helps to reduce the number of queries performed against database if some related models are only used when a specific condition is met. For example:
$customer = Customer::find()->where(['id' => 123])->one();if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) { $customer->loadRelations('orders.items');}Parameters
| Parameter | Type | Description |
|---|---|---|
$relationNames | string| | The names of the relations of this model to be loaded from database. See ActiveQueryInterface::with() on how to specify this argument. |
$asArray | bool | Whether to load each relation as an array or an object (if the relation itself does not specify that). |
Returns
mixed
Since
2.0.50
loadRelationsFor()
Section titled “loadRelationsFor() ”public static function loadRelationsFor(yii\db\TModels &$models, string|array $relationNames, bool $asArray = false): mixedEager loads related models for the already loaded primary models.
Helps to reduce the number of queries performed against database if some related models are only used when a specific condition is met. For example:
$customers = Customer::find()->where(['country_id' => 123])->all();if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) { Customer::loadRelationsFor($customers, 'orders.items');}Parameters
| Parameter | Type | Description |
|---|---|---|
$models | yii\ | Array of primary models. Each model should have the same type and can be: - an active record instance; - active record instance represented by array (i.e. active record was loaded using ActiveQuery::asArray()). |
$relationNames | string| | The names of the relations of primary models to be loaded from database. See ActiveQueryInterface::with() on how to specify this argument. |
$asArray | bool | Whether to load each related model as an array or an object (if the relation itself does not specify that). |
Returns
mixed
Since
2.0.50
markAttributeDirty()
Section titled “markAttributeDirty() ”public function markAttributeDirty(string $name): mixedMarks 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
| Parameter | Type | Description |
|---|---|---|
$name | string | The attribute name |
Returns
mixed
offsetExists()
Section titled “offsetExists() ”public function offsetExists(mixed $offset): boolReturns whether there is an element at the specified offset.
This method is required by the interface ArrayAccess.
Parameters
| Parameter | Type | Description |
|---|---|---|
$offset | mixed | The offset to check on |
Returns
bool: Whether there is an element at the specified offset.
offsetUnset()
Section titled “offsetUnset() ”public function offsetUnset(mixed $offset): mixedSets 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
| Parameter | Type | Description |
|---|---|---|
$offset | mixed | The offset to unset element |
Returns
mixed
optimisticLock()
Section titled “optimisticLock() ”public function optimisticLock(): string|nullReturns 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:
- 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. - 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.
- In the Web form that collects the user input, add a hidden field that stores the lock version of the record being updated.
- In the controller action that does the data updating, try to catch the
StaleObjectExceptionand implement necessary business logic (e.g. merging the changes, prompting stated data) to resolve the conflict.
Returns
string|null: The column name that stores the lock version of a table row. If null is returned (default implemented), optimistic locking will not be supported.
populateRecord()
Section titled “populateRecord() ”public static function populateRecord(yii\db\BaseActiveRecord $record, array $row): mixedPopulates 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
| Parameter | Type | Description |
|---|---|---|
$record | BaseActiveRecord | The record to be populated. In most cases this will be an instance created by instantiate() beforehand. |
$row | array | Attribute values (name => value) |
Returns
mixed
populateRelation()
Section titled “populateRelation() ”public function populateRelation(string $name, yii\db\ActiveRecordInterface|array|null $records): mixedPopulates the named relation with the related records.
Note that this method does not check if the relation exists or not.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The relation name, e.g. orders for a relation defined via getOrders() method (case-sensitive). |
$records | ActiveRecordInterface| | The related records to be populated into the relation. |
Returns
mixed
See also
refresh()
Section titled “refresh() ”public function refresh(): boolRepopulates 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.
save()
Section titled “save() ”public function save(bool $runValidation = true, array|null $attributeNames = null): boolSaves 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
| Parameter | Type | Description |
|---|---|---|
$runValidation | bool | 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. |
Returns
bool: Whether the saving succeeded (i.e. no validation errors occurred).
Throws
Exception: in case update or insert failed.
setAttribute()
Section titled “setAttribute() ”public function setAttribute(string $name, mixed $value): mixedSets the named attribute value.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The attribute name |
$value | mixed | The attribute value. |
Returns
mixed
Throws
yii\base\InvalidArgumentException: if the named attribute does not exist.
See also
setIsNewRecord()
Section titled “setIsNewRecord() ”public function setIsNewRecord(bool $value): mixedSets the value indicating whether the record is new.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | bool | Whether the record is new and should be inserted when calling save(). |
Returns
mixed
See also
setOldAttribute()
Section titled “setOldAttribute() ”public function setOldAttribute(string $name, mixed $value): mixedSets the old value of the named attribute.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The attribute name |
$value | mixed | The old attribute value. |
Returns
mixed
Throws
yii\base\InvalidArgumentException: if the named attribute does not exist.
See also
setOldAttributes()
Section titled “setOldAttributes() ”public function setOldAttributes(array|null $values): mixedSets the old attribute values.
All existing old attribute values will be discarded.
Parameters
| Parameter | Type | Description |
|---|---|---|
$values | array| | Old attribute values to be set. If set to null this record is considered to be new. |
Returns
mixed
unlink()
Section titled “unlink() ”public function unlink(string $name, yii\db\ActiveRecordInterface $model, bool $delete = false): mixedDestroys the relationship between two models.
The model with the foreign key of the relationship will be deleted if $delete is true.
Otherwise, the foreign key will be set null and the model will be saved without validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method. |
$model | ActiveRecordInterface | The model to be unlinked from the current one. You have to make sure that the model is really related with the current model as this method does not check this. |
$delete | bool | Whether to delete the model that contains the foreign key. If false, the model’s foreign key will be set null and saved. If true, the model containing the foreign key will be deleted. |
Returns
mixed
Throws
yii\base\InvalidCallException: if the models cannot be unlinkedExceptionStaleObjectException
unlinkAll()
Section titled “unlinkAll() ”public function unlinkAll(string $name, bool $delete = false): mixedDestroys the relationship in current model.
The model with the foreign key of the relationship will be deleted if $delete is true.
Otherwise, the foreign key will be set null and the model will be saved without validation.
Note that to destroy the relationship without removing records make sure your keys can be set to null
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method. |
$delete | bool | Whether to delete the model that contains the foreign key. Note that the deletion will be performed using deleteAll(), 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
update()
Section titled “update() ”public function update(bool $runValidation = true, array|null $attributeNames = null): int|falseSaves the changes to this active record into the associated database table.
This method performs the following steps in order:
- call
beforeValidate()when$runValidationistrue. IfbeforeValidate()returnsfalse, the rest of the steps will be skipped; - call
afterValidate()when$runValidationistrue. If validation failed, the rest of the steps will be skipped; - call
beforeSave(). IfbeforeSave()returnsfalse, the rest of the steps will be skipped; - save the record into database. If this fails, it will skip the rest of the steps;
- 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
| Parameter | Type | Description |
|---|---|---|
$runValidation | bool | 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. |
Returns
int|false: The number of rows affected, or false if validation fails or beforeSave() stops the updating process.
Throws
StaleObjectException: if optimistic locking is enabled and the data being updated is outdated.Exception: in case update failed.
updateAll()
Section titled “updateAll() ”public static function updateAll(array $attributes, string|array $condition = ''): intUpdates the whole table using the provided attribute values and conditions.
For example, to change the status to be 1 for all customers whose status is 2:
Customer::updateAll(['status' => 1], 'status = 2');Parameters
| Parameter | Type | Description |
|---|---|---|
$attributes | array | Attribute values (name-value pairs) to be saved into the table |
$condition | string| | The 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
yii\base\NotSupportedException: if not overridden
updateAllCounters()
Section titled “updateAllCounters() ”public static function updateAllCounters(array $counters, string|array $condition = ''): intUpdates the whole table using the provided counter changes and conditions.
For example, to increment all customers’ age by 1,
Customer::updateAllCounters(['age' => 1]);Parameters
| Parameter | Type | Description |
|---|---|---|
$counters | array | The counters to be updated (attribute name => increment value). Use negative values if you want to decrement the counters. |
$condition | string| | The 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
yii\base\NotSupportedException: if not overrided
updateAttributes()
Section titled “updateAttributes() ”public function updateAttributes(array $attributes): intUpdates 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
| Parameter | Type | Description |
|---|---|---|
$attributes | array | The attributes (names or name-value pairs) to be updated |
Returns
int: The number of rows affected.
updateCounters()
Section titled “updateCounters() ”public function updateCounters(array $counters): boolUpdates 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
| Parameter | Type | Description |
|---|---|---|
$counters | array | The counters to be updated (attribute name => increment value) Use negative values if you want to decrement the counters. |
Returns
bool: Whether the saving is successful
See also
createRelationQuery()
Section titled “createRelationQuery() ”protected function createRelationQuery(string $class, array $link, bool $multiple): yii\db\ActiveQueryInterfaceCreates a query instance for has-one or has-many relation.
Parameters
| Parameter | Type | Description |
|---|---|---|
$class | string | The class name of the related record. |
$link | array | The primary-foreign key constraint. |
$multiple | bool | Whether this query represents a relation to more than one record. |
Returns
ActiveQueryInterface: The relational query object.
Since
2.0.12
See also
refreshInternal()
Section titled “refreshInternal() ”protected function refreshInternal(yii\db\BaseActiveRecord $record): boolRepopulates this active record with the latest data from a newly fetched instance.
Parameters
| Parameter | Type | Description |
|---|---|---|
$record | BaseActiveRecord | The record to take attributes from. |
Returns
bool: Whether refresh was successful.
Since
2.0.13
See also
updateInternal()
Section titled “updateInternal() ”protected function updateInternal(array|null $attributes = null): int|falseParameters
| Parameter | Type | Description |
|---|---|---|
$attributes | array| | Attributes to update |
Returns
int|false: The number of rows affected, or false if beforeSave() stops the updating process.
Throws
See also