Abstract Class yii\db\BaseActiveRecord
Inheritance | yii\db\BaseActiveRecord » yii\base\Model » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | ArrayAccess, IteratorAggregate, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface, yii\db\ActiveRecordInterface |
Uses Traits | yii\base\ArrayableTrait, yii\base\StaticInstanceTrait |
Subclasses | kartik\tree\models\Tree, yii\db\ActiveRecord |
Available since version | 2.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
Property | Type | Description | Defined 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. Empty array is returned
if no error. See getErrors() for detailed description. Note that when returning errors for all attributes,
the result is a two-dimensional array, like the following: ` php [ 'username' => [ 'Username is required.',
'Username must contain only word characters.', ], 'email' => [ 'Email address is invalid.', ] ] ` . |
yii\base\Model |
$firstErrors | array | The first errors. The array keys are the attribute names, and the array values are the corresponding error messages. An empty array will be returned if there is no error. | 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). Note that the type of this property differs in getter and setter. See getOldAttributes() and setOldAttributes() for details. | yii\db\BaseActiveRecord |
$oldPrimaryKey | mixed | The old primary key value. An array (column name => column value) is returned if the primary key is composite. A string is returned otherwise (null will be returned if the key value is null). | yii\db\BaseActiveRecord |
$primaryKey | mixed | The primary key value. An array (column name => column value) is returned if the primary key is composite. A string is returned otherwise (null will be returned if the key value is null). | 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. Defaults to SCENARIO_DEFAULT. | yii\base\Model |
$validators | ArrayObject|yii\validators\Validator[] | All the validators declared in the model. | yii\base\Model |
Public Methods
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | yii\base\Component |
__clone() | This method is called after the object is created by cloning an existing one. | yii\base\Model |
__construct() | Constructor. | yii\base\BaseObject |
__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\BaseObject |
clearErrors() | Removes errors for all attributes or a single attribute. | yii\base\Model |
createValidators() | Creates validator objects based on the validation rules specified in rules(). | yii\base\Model |
delete() | Deletes the table row corresponding to this active record. | 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 |
getErrorSummary() | Returns the errors for all attributes as a one-dimensional array. | yii\base\Model |
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() | 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\Component |
hasOne() | Declares a has-one relation. |
yii\db\BaseActiveRecord |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\base\Component |
init() | Initializes the object. | yii\db\BaseActiveRecord |
insert() | Inserts the record into the database using the attribute values of this record. | yii\db\ActiveRecordInterface |
instance() | Returns static class instance, which can be used to obtain meta information. | yii\base\StaticInstanceTrait |
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() | yii\db\BaseActiveRecord | |
offsetGet() | yii\base\Model | |
offsetSet() | 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
Method | Description | Defined By |
---|---|---|
createRelationQuery() | Creates a query instance for has-one or has-many relation. |
yii\db\BaseActiveRecord |
extractFieldsFor() | Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id". | yii\base\ArrayableTrait |
extractRootFields() | Extracts the root field names from nested fields. | yii\base\ArrayableTrait |
findByCondition() | Finds ActiveRecord instance(s) by the given condition. | yii\db\BaseActiveRecord |
refreshInternal() | Repopulates this active record with the latest data from a newly fetched instance. | yii\db\BaseActiveRecord |
resolveFields() | Determines which fields can be returned by toArray(). | yii\base\ArrayableTrait |
updateInternal() | yii\db\BaseActiveRecord |
Events
Event | Type | Description | Defined By |
---|---|---|---|
EVENT_AFTER_DELETE | \yii\db\Event | An event that is triggered after a record is deleted. | yii\db\BaseActiveRecord |
EVENT_AFTER_FIND | \yii\db\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\db\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\db\Event | An event that is triggered when the record is initialized via init(). | yii\db\BaseActiveRecord |
Constants
Constant | Value | Description | Defined By |
---|---|---|---|
SCENARIO_DEFAULT | 'default' | The name of the default scenario. | yii\base\Model |
Property Details
The changed attribute values (name-value pairs).
Whether the record is new and should be inserted when calling save().
The old attribute values (name-value pairs). Note that the type of this property differs in getter and setter. See getOldAttributes() and setOldAttributes() for details.
The old primary key value. An array (column name => column value) is returned if the primary key is composite. A string is returned otherwise (null will be returned if the key value is null).
The primary key value. An array (column name => column value) is returned if the primary key is composite. A string is returned otherwise (null will be returned if the key value is null).
An array of related records indexed by relation names.
Method Details
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\InvalidArgumentException | if relation name is wrong |
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 |
---|
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 |
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 |
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 ( ) |
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 ( ) |
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 ( ) |
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 |
$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.
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. |
This method is invoked before deleting a record.
The default implementation raises the EVENT_BEFORE_DELETE event. When overriding this method, make sure you call the parent implementation like the following:
public function beforeDelete()
{
if (!parent::beforeDelete()) {
return false;
}
// ...custom code here...
return true;
}
public boolean beforeDelete ( ) | ||
return | boolean | Whether the record should be deleted. Defaults to |
---|
This method is called at the beginning of inserting or updating a record.
The default implementation will trigger an EVENT_BEFORE_INSERT event when $insert
is true
,
or an EVENT_BEFORE_UPDATE event if $insert
is false
.
When overriding this method, make sure you call the parent implementation like the following:
public function beforeSave($insert)
{
if (!parent::beforeSave($insert)) {
return false;
}
// ...custom code here...
return true;
}
public boolean beforeSave ( $insert ) | ||
$insert | boolean | Whether this method called while inserting a record.
If |
return | boolean | Whether the insertion or updating should continue.
If |
---|
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 |
---|
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 |
---|
protected yii\db\ActiveQueryInterface createRelationQuery ( $class, $link, $multiple ) | ||
$class | string | The class name of the related record. |
$link | array | The primary-foreign key constraint. |
$multiple | boolean | Whether this query represents a relation to more than one record. |
return | yii\db\ActiveQueryInterface | The relational query object. |
---|
Deletes the table row corresponding to this active record.
This method performs the following steps in order:
- call beforeDelete(). If the method returns
false
, 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.
public integer|false delete ( ) | ||
return | integer|false | The number of rows deleted, or |
---|---|---|
throws | yii\db\StaleObjectException | if optimistic locking is enabled and the data being deleted is outdated. |
throws | yii\db\Exception | in case delete failed. |
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|null | 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. |
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. |
---|
Returns the list of fields that can be expanded further and returned by toArray().
The default implementation returns the names of the relations that have been populated into this record.
This method is similar to fields() except that the list of fields returned by this method are not returned by default by toArray(). Only when field names to be expanded are explicitly specified when calling toArray(), will their values be exported.
The default implementation returns an empty array.
You may override this method to return a list of expandable fields based on some context information (e.g. the current application user).
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. |
---|
Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.
The default implementation returns the names of the columns whose values have been populated into this record.
A field is a named element in the returned array by toArray().
This method should return an array of field names or field definitions. If the former, the field name will be treated as an object property name whose value will be used as the field value. If the latter, the array key should be the field name while the array value should be the corresponding field definition which can be either an object property name or a PHP callable returning the corresponding field value. The signature of the callable should be:
function ($model, $field) {
// return field value
}
For example, the following code declares four fields:
email
: the field name is the same as the property nameemail
;firstName
andlastName
: the field names arefirstName
andlastName
, and their values are obtained from thefirst_name
andlast_name
properties;fullName
: the field name isfullName
. Its value is obtained by concatenatingfirst_name
andlast_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.
public array fields ( ) | ||
return | array | The list of field names or field definitions. |
---|
Returns a list of active record models that match the specified primary key value(s) or a set of column values.
The method accepts:
- a scalar value (integer or string): query by a single primary key value and return an array containing the corresponding record (or an empty array if not found).
- a non-associative array: query by a list of primary key values and return the
corresponding records (or an empty array if none was found).
Note that an empty condition will result in an empty result as it will be interpreted as a search for
primary keys and not an empty
WHERE
condition. - an associative array of name-value pairs: query by a set of attribute values and return an array of records
matching all of them (or an empty array if none was found). Note that
['id' => 1, 2]
is treated as a non-associative array. Column names are limited to current records table columns for SQL DBMS, or filtered otherwise to be limted to simple filter conditions. - a yii\db\Expression: The expression will be used directly. (@since 2.0.37)
This method will automatically call the all()
method and return an array of ActiveRecord
instances.
Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work. If you need to specify more complex conditions, use find() in combination with where() instead.
See the following code for usage examples:
// find the customers whose primary key value is 10
$customers = Customer::findAll(10);
// the above code is equivalent to:
$customers = Customer::find()->where(['id' => 10])->all();
// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findAll([10, 11, 12]);
// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();
// find customers whose age is 30 and whose status is 1
$customers = Customer::findAll(['age' => 30, 'status' => 1]);
// the above code is equivalent to:
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();
If you need to pass user input to this method, make sure the input value is scalar or in case of array condition, make sure the array structure can not be changed from the outside:
// yii\web\Controller ensures that $id is scalar
public function actionView($id)
{
$model = Post::findOne($id);
// ...
}
// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);
// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
$model = Post::findOne(Yii::$app->request->get('id'));
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. |
---|
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 |
Returns a single active record model instance by a primary key or an array of column values.
The method accepts:
- a scalar value (integer or string): query by a single primary key value and return the
corresponding record (or
null
if not found). - a non-associative array: query by a list of primary key values and return the
first record (or
null
if not found). - an associative array of name-value pairs: query by a set of attribute values and return a single record
matching all of them (or
null
if not found). Note that['id' => 1, 2]
is treated as a non-associative array. Column names are limited to current records table columns for SQL DBMS, or filtered otherwise to be limited to simple filter conditions. - a yii\db\Expression: The expression will be used directly. (@since 2.0.37)
That this method will automatically call the one()
method and return an ActiveRecord
instance.
Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work. If you need to specify more complex conditions, use find() in combination with where() instead.
See the following code for usage examples:
// find a single customer whose primary key value is 10
$customer = Customer::findOne(10);
// the above code is equivalent to:
$customer = Customer::find()->where(['id' => 10])->one();
// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findOne([10, 11, 12]);
// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->one();
// find the first customer whose age is 30 and whose status is 1
$customer = Customer::findOne(['age' => 30, 'status' => 1]);
// the above code is equivalent to:
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
If you need to pass user input to this method, make sure the input value is scalar or in case of array condition, make sure the array structure can not be changed from the outside:
// yii\web\Controller ensures that $id is scalar
public function actionView($id)
{
$model = Post::findOne($id);
// ...
}
// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);
// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
$model = Post::findOne(Yii::$app->request->get('id'));
public static static|null findOne ( $condition ) | ||
$condition | mixed | Primary key value or a set of column values |
return | static|null | ActiveRecord instance matching the condition, or |
---|
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. |
---|
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 |
---|
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 |
---|
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) |
---|
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(). |
---|
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. |
---|
Returns the old attribute values.
public array getOldAttributes ( ) | ||
return | array | The old attribute values (name-value pairs) |
---|
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 |
return | mixed | The old primary key value. An array (column name => column value) is returned if the primary key
is composite or |
---|---|---|
throws | yii\db\Exception | if the AR model does not have a primary key |
Returns the primary key value(s).
public mixed getPrimaryKey ( $asArray = false ) | ||
$asArray | boolean | Whether to return the primary key value as an array. If |
return | mixed | The primary key value. An array (column name => column value) is returned if the primary key
is composite or |
---|
Returns all populated related records.
See also getRelation().
public array getRelatedRecords ( ) | ||
return | array | An array of related records indexed by relation names. |
---|
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|null getRelation ( $name, $throwException = true ) | ||
$name | string | The relation name, e.g. |
$throwException | boolean | Whether to throw exception if the relation does not exist. |
return | yii\db\ActiveQueryInterface|yii\db\ActiveQuery|null | The relational query object. If the relation does not exist
and |
---|---|---|
throws | yii\base\InvalidArgumentException | if the named relation does not exist. |
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. |
---|
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::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 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 |
return | yii\db\ActiveQueryInterface | The relational query object. |
---|
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::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 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 |
return | yii\db\ActiveQueryInterface | The relational query object. |
---|
Initializes the object.
This method is called at the end of the constructor. The default implementation will trigger an EVENT_INIT event.
public void init ( ) |
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 |
---|
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 |
return | boolean | Whether the attribute has been changed |
---|
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 |
---|
Check whether the named relation has been populated with records.
See also getRelation().
public boolean isRelationPopulated ( $name ) | ||
$name | string | The relation name, e.g. |
return | boolean | Whether relation has been populated with records. |
---|
Establishes the relationship between two models.
The relationship is established by setting the foreign key value(s) in one model to be the corresponding primary key value(s) in the other model. The model with the foreign key will be saved into database without performing validation and without events/behaviors.
If the relationship involves a junction table, a new row will be inserted into the junction table which contains the primary key values from both models.
Note that this method requires that the primary key value is not null.
public void link ( $name, $model, $extraColumns = [] ) | ||
$name | string | The case sensitive name of the relationship, e.g. |
$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. |
---|
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 |
public void offsetExists ( $offset ) | ||
$offset |
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 |
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:
- 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 yii\db\StaleObjectException and implement necessary business logic (e.g. merging the changes, prompting stated data) to resolve the conflict.
public string|null optimisticLock ( ) | ||
return | string|null | The column name that stores the lock version of a table row.
If |
---|
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) |
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. |
$records | yii\db\ActiveRecordInterface|array|null | The related records to be populated into the relation. |
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 |
---|
Repopulates this active record with the latest data from a newly fetched instance.
See also refresh().
protected boolean refreshInternal ( $record ) | ||
$record | yii\db\BaseActiveRecord | The record to take attributes from. |
return | boolean | Whether refresh was successful. |
---|
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 |
$attributeNames | array|null | List of attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved. |
return | boolean | Whether the saving succeeded (i.e. no validation errors occurred). |
---|
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\InvalidArgumentException | if the named attribute does not exist. |
---|
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(). |
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\InvalidArgumentException | if the named attribute does not exist. |
---|
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 |
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. |
$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 |
throws | yii\base\InvalidCallException | if the models cannot be unlinked |
---|---|---|
throws | yii\db\Exception | |
throws | yii\db\StaleObjectException |
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. |
$delete | boolean | 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. |
Saves the changes to this active record into the associated database table.
This method performs the following steps in order:
- call beforeValidate() when
$runValidation
istrue
. If beforeValidate() returnsfalse
, the rest of the steps will be skipped; - call afterValidate() when
$runValidation
istrue
. If validation failed, the rest of the steps will be skipped; - call beforeSave(). If beforeSave() returns
false
, 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
}
public integer|false update ( $runValidation = true, $attributeNames = null ) | ||
$runValidation | boolean | Whether to perform validation (calling validate())
before saving the record. Defaults to |
$attributeNames | array|null | List of attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved. |
return | integer|false | The number of rows affected, or |
---|---|---|
throws | yii\db\StaleObjectException | if optimistic locking is enabled and the data being updated is outdated. |
throws | yii\db\Exception | in case update failed. |
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 |
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 |
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. |
---|
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 |
---|
See also update().
protected integer|false updateInternal ( $attributes = null ) | ||
$attributes | array|null | 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
An event that is triggered after a record is deleted.
An event that is triggered after the record is created and populated with query result.
An event that is triggered after a record is inserted.
An event that is triggered after a record is refreshed.
An event that is triggered after a record is updated.
An event that is triggered before deleting a record.
You may set yii\base\ModelEvent::$isValid to be false
to stop the deletion.
An event that is triggered before inserting a record.
You may set yii\base\ModelEvent::$isValid to be false
to stop the insertion.
An event that is triggered before updating a record.
You may set yii\base\ModelEvent::$isValid to be false
to stop the update.
An event that is triggered when the record is initialized via init().