Abstract Class yii\mongodb\ActiveRecord

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

ActiveRecord is the base class for classes representing Mongo documents in terms of objects.

Public Methods

Hide inherited methods

MethodDescriptionDefined 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\Component
__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 model. yii\mongodb\ActiveRecord
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() {@inheritdoc} yii\db\BaseActiveRecord
canSetProperty() {@inheritdoc} 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
collectionName() Declares the name of the Mongo collection associated with this AR class. yii\mongodb\ActiveRecord
createValidators() Creates validator objects based on the validation rules specified in rules(). yii\base\Model
delete() Deletes the document corresponding to this active record from the collection. yii\mongodb\ActiveRecord
deleteAll() Deletes documents in the collection using the provided conditions. yii\mongodb\ActiveRecord
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\mongodb\ActiveRecord
extraFields() Returns the list of fields that can be expanded further and returned by toArray(). yii\base\ArrayableTrait
fields() Returns the list of fields that should be returned by default by toArray() when no specific fields are specified. yii\base\ArrayableTrait
find() {@inheritdoc} yii\mongodb\ActiveRecord
findAll() Returns a list of active record models that match the specified primary key value(s) or a set of column values. yii\db\ActiveRecordInterface
findOne() Returns a single active record model instance by a primary key or an array of column values. yii\db\ActiveRecordInterface
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 \yii\base\scenario. yii\base\Model
getAttribute() Returns the named attribute value. yii\db\ActiveRecordInterface
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
getCollection() Return the Mongo collection instance for this AR class. yii\mongodb\ActiveRecord
getDb() Returns the Mongo connection used by this AR class. yii\mongodb\ActiveRecord
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 (not saved in the database). yii\db\ActiveRecordInterface
getIterator() Returns an iterator for traversing the attributes in the model. yii\base\Model
getOldAttribute() Returns the old value of the named attribute. yii\db\BaseActiveRecord
getOldAttributes() Returns the old attribute values. yii\db\BaseActiveRecord
getOldPrimaryKey() Returns the old primary key value(s). yii\db\ActiveRecordInterface
getPrimaryKey() Returns the primary key value(s). yii\db\ActiveRecordInterface
getRelatedRecords() Returns all populated related records. yii\db\BaseActiveRecord
getRelation() Returns the relation object with the specified name. yii\db\ActiveRecordInterface
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 record has an attribute with the specified name. yii\db\ActiveRecordInterface
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 a row into the associated Mongo collection using the attribute values of this record. yii\mongodb\ActiveRecord
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\ActiveRecordInterface
isRelationPopulated() Check whether the named relation has been populated with records. yii\db\BaseActiveRecord
link() Establishes the relationship between two records. yii\db\ActiveRecordInterface
load() Populates the model with input data. yii\base\Model
loadMultiple() Populates a set of models with the data from end user. yii\base\Model
markAttributeDirty() Marks an attribute dirty. yii\db\BaseActiveRecord
off() Detaches an existing event handler from this component. yii\base\Component
offsetExists() Returns whether there is an element at the specified offset. yii\db\BaseActiveRecord
offsetGet() Returns the element at the specified offset. yii\base\Model
offsetSet() Sets the element at the specified offset. yii\base\Model
offsetUnset() Sets the element value at the specified offset to null. yii\db\BaseActiveRecord
on() Attaches an event handler to an event. yii\base\Component
onUnsafeAttribute() This method is invoked when an unsafe attribute is being massively assigned. yii\base\Model
optimisticLock() Returns the name of the column that stores the lock version for implementing optimistic locking. yii\db\BaseActiveRecord
populateRecord() Populates an active record object using a row of data from the database/storage. yii\db\BaseActiveRecord
populateRelation() Populates the named relation with the related records. yii\db\ActiveRecordInterface
primaryKey() Returns the primary key name(s) for this AR class. yii\mongodb\ActiveRecord
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\ActiveRecordInterface
scenarios() Returns a list of scenarios and the corresponding active attributes. yii\base\Model
setAttribute() Sets the named attribute value. yii\db\ActiveRecordInterface
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() {@inheritdoc} yii\mongodb\ActiveRecord
trigger() Triggers an event. yii\base\Component
unlink() Destroys the relationship between two records. yii\db\ActiveRecordInterface
unlinkAll() Destroys the relationship in current model. yii\db\BaseActiveRecord
update() Saves the changes to this active record into the database. yii\db\ActiveRecordInterface
updateAll() Updates all documents in the collection using the provided attribute values and conditions. yii\mongodb\ActiveRecord
updateAllCounters() Updates all documents in the collection using the provided counter changes and conditions. yii\mongodb\ActiveRecord
updateAttributes() Updates the specified attributes. yii\db\BaseActiveRecord
updateCounters() Updates one or several counter columns for the current AR object. yii\db\BaseActiveRecord
validate() Performs the data validation. yii\base\Model
validateMultiple() Validates multiple models. yii\base\Model

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
createRelationQuery() Creates a query instance for has-one or has-many relation. yii\db\BaseActiveRecord
deleteInternal() yii\mongodb\ActiveRecord
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
insertInternal() yii\mongodb\ActiveRecord
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\mongodb\ActiveRecord

Events

Hide inherited events

EventTypeDescriptionDefined 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

Hide inherited constants

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

Method Details

attributes() public method

Returns the list of all attribute names of the model.

This method must be overridden by child classes to define available attributes. Note: primary key attribute "_id" should be always present in returned array. For example:

public function attributes()
{
    return ['_id', 'name', 'address', 'status'];
}
public array attributes ( )
return array

List of attribute names.

throws yii\base\InvalidConfigException

if not implemented

collectionName() public static method

Declares the name of the Mongo collection associated with this AR class.

Collection name can be either a string or array:

  • if string considered as the name of the collection inside the default database.
  • if array - first element considered as the name of the database, second - as name of collection inside that database

By default this method returns the class name as the collection name by calling yii\helpers\Inflector::camel2id(). For example, 'Customer' becomes 'customer', and 'OrderItem' becomes 'order_item'. You may override this method if the collection is not named after this convention.

public static string|array collectionName ( )
return string|array

The collection name

delete() public method

Deletes the document corresponding to this active record from the collection.

This method performs the following steps in order:

  1. call beforeDelete(). If the method returns false, it will skip the rest of the steps;
  2. delete the document from the collection;
  3. call afterDelete().

In the above step 1 and 3, events named EVENT_BEFORE_DELETE and EVENT_AFTER_DELETE will be raised by the corresponding methods.

public integer|boolean delete ( )
return integer|boolean

The number of documents deleted, or false if the deletion is unsuccessful for some reason. Note that it is possible the number of documents deleted is 0, even though the deletion execution is successful.

throws yii\db\StaleObjectException

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

throws Exception

in case delete failed.

deleteAll() public static method

Deletes documents in the collection using the provided conditions.

WARNING: If you do not specify any condition, this method will delete documents rows in the collection.

For example, to delete all customers whose status is 3:

Customer::deleteAll(['status' => 3]);
public static integer deleteAll ( $condition = [], $options = [] )
$condition array

Description of the objects to delete. Please refer to yii\mongodb\Query::where() on how to specify this parameter.

$options array

List of options in format: optionName => optionValue.

return integer

The number of documents deleted.

deleteInternal() protected method
protected void deleteInternal ( )
throws yii\db\StaleObjectException
equals() public method

Returns a value indicating whether the given active record is the same as the current one.

The comparison is made by comparing the collection names and the primary key values of the two active records. If one of the records \yii\mongodb\isNewRecord they are also considered not equal.

public boolean equals ( $record )
$record yii\mongodb\ActiveRecord

Record to compare to

return boolean

Whether the two active records refer to the same row in the same Mongo collection.

find() public static method

{@inheritdoc}

public static yii\mongodb\ActiveQuery find ( )
return yii\mongodb\ActiveQuery

The newly created yii\mongodb\ActiveQuery instance.

getCollection() public static method

Return the Mongo collection instance for this AR class.

public static yii\mongodb\Collection getCollection ( )
return yii\mongodb\Collection

Collection instance.

getDb() public static method

Returns the Mongo connection used by this AR class.

By default, the "mongodb" application component is used as the Mongo connection. You may override this method if you want to use a different database connection.

public static yii\mongodb\Connection getDb ( )
return yii\mongodb\Connection

The database connection used by this AR class.

insert() public method

Inserts a row into the associated Mongo collection using the attribute values of this record.

This method performs the following steps in order:

  1. call beforeValidate() when $runValidation is true. If validation fails, it will skip the rest of the steps;
  2. call afterValidate() when $runValidation is true.
  3. call beforeSave(). If the method returns false, it will skip the rest of the steps;
  4. insert the record into collection. If this fails, it will skip the rest of the steps;
  5. call afterSave();

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

Only the \yii\mongodb\dirtyAttributes will be inserted into database.

If the primary key is null during insertion, it will be populated with the actual value after insertion.

For example, to insert a customer record:

$customer = new Customer();
$customer->name = $name;
$customer->email = $email;
$customer->insert();
public boolean insert ( $runValidation true, $attributes null )
$runValidation boolean

Whether to perform validation before saving the record. If the validation fails, the record will not be inserted into the collection.

$attributes array

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

return boolean

Whether the attributes are valid and the record is inserted successfully.

throws Exception

in case insert failed.

insertInternal() protected method
protected void insertInternal ( $attributes null )
$attributes
primaryKey() public static method

Returns the primary key name(s) for this AR class.

The default implementation will return ['_id'].

Note that an array should be returned even for a collection with single primary key.

public static string[] primaryKey ( )
return string[]

The primary keys of the associated Mongo collection.

toArray() public method

{@inheritdoc}

public void toArray ( array $fields = [], array $expand = [], $recursive true )
$fields
$expand
$recursive
updateAll() public static method

Updates all documents in the collection 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 = [], $options = [] )
$attributes array

Attribute values (name-value pairs) to be saved into the collection

$condition array

Description of the objects to update. Please refer to yii\mongodb\Query::where() on how to specify this parameter.

$options array

List of options in format: optionName => optionValue.

return integer

The number of documents updated.

updateAllCounters() public static method

Updates all documents in the collection 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 = [], $options = [] )
$counters array

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

$condition array

Description of the objects to update. Please refer to yii\mongodb\Query::where() on how to specify this parameter.

$options array

List of options in format: optionName => optionValue.

return integer

The number of documents updated.

updateInternal() protected method
protected void updateInternal ( $attributes null )
$attributes
throws yii\db\StaleObjectException