Abstract Class yii\mongodb\file\ActiveRecord

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

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

To specify source file use the \yii\mongodb\file\file attribute. It can be specified in one of the following ways:

  • string - full name of the file, which content should be stored in GridFS
  • \yii\web\UploadedFile - uploaded file instance, which content should be stored in GridFS

For example:

$record = new ImageFile();
$record->file = '/path/to/some/file.jpg';
$record->save();

You can also specify file content via \yii\mongodb\file\newFileContent attribute:

$record = new ImageFile();
$record->newFileContent = 'New file content';
$record->save();

Note: \yii\mongodb\file\newFileContent always takes precedence over \yii\mongodb\file\file.

Public Properties

Hide inherited properties

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

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Object
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\Object
__get() PHP getter magic method. yii\db\BaseActiveRecord
__isset() Checks if a property value is null. yii\db\BaseActiveRecord
__set() PHP setter magic method. yii\db\BaseActiveRecord
__unset() Sets a component property to be null. yii\db\BaseActiveRecord
activeAttributes() Returns the attribute names that are subject to validation in the current scenario. yii\base\Model
addError() Adds a new error to the specified attribute. yii\base\Model
addErrors() Adds a list of errors. yii\base\Model
afterDelete() This method is invoked after deleting a record. yii\db\BaseActiveRecord
afterFind() This method is called when the AR object is created and populated with the query result. yii\db\BaseActiveRecord
afterRefresh() This method is called when the AR object is refreshed. yii\db\BaseActiveRecord
afterSave() This method is called at the end of inserting or updating a record. yii\db\BaseActiveRecord
afterValidate() This method is invoked after validation ends. yii\base\Model
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
attributeHints() Returns the attribute hints. yii\base\Model
attributeLabels() Returns the attribute labels. yii\base\Model
attributes() Returns the list of all attribute names of the model. yii\mongodb\file\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() Returns a value indicating whether a property can be read. yii\db\BaseActiveRecord
canSetProperty() Returns a value indicating whether a property can be set. yii\db\BaseActiveRecord
className() Returns the fully qualified name of this class. yii\base\Object
clearErrors() Removes errors for all attributes or a single attribute. yii\base\Model
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 record from the database. yii\db\ActiveRecordInterface
deleteAll() Deletes records using the provided conditions. yii\db\ActiveRecordInterface
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\ActiveRecordInterface
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() Creates an \yii\mongodb\file\ActiveQueryInterface instance for query purpose. yii\mongodb\file\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 $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 GridFS collection instance for this AR class. yii\mongodb\file\ActiveRecord
getDb() Returns the connection used by this AR class. yii\db\ActiveRecordInterface
getDirtyAttributes() Returns the attribute values that have been modified since they are loaded or saved most recently. yii\db\BaseActiveRecord
getErrors() Returns the errors for all attributes or a single attribute. yii\base\Model
getFileContent() Returns the associated file content. yii\mongodb\file\ActiveRecord
getFileResource() This method returns a stream resource that can be used with all file functions in PHP, which deal with reading files. The contents of the file are pulled out of MongoDB on the fly, so that the whole file does not have to be loaded into memory first. yii\mongodb\file\ActiveRecord
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\Object
hasOne() Declares a has-one relation. yii\db\BaseActiveRecord
hasProperty() Returns a value indicating whether a property is defined. yii\base\Object
init() Initializes the object. yii\db\BaseActiveRecord
insert() Inserts the record into the database using the attribute values of this record. yii\db\ActiveRecordInterface
instantiate() Creates an active record instance. yii\db\BaseActiveRecord
isAttributeActive() Returns a value indicating whether the attribute is active in the current scenario. yii\base\Model
isAttributeChanged() Returns a value indicating whether the named attribute has been changed. yii\db\BaseActiveRecord
isAttributeRequired() Returns a value indicating whether the attribute is required. yii\base\Model
isAttributeSafe() Returns a value indicating whether the attribute is safe for massive assignments. yii\base\Model
isPrimaryKey() Returns a value indicating whether the given set of attributes represents the primary key for this model yii\db\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\db\ActiveRecordInterface
refresh() Repopulates this active record with the latest data. yii\db\BaseActiveRecord
refreshFile() Refreshes the \yii\mongodb\file\file attribute from file collection, using current primary key. yii\mongodb\file\ActiveRecord
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() Converts the model into an array. yii\base\ArrayableTrait
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 records using the provided attribute values and conditions. yii\db\ActiveRecordInterface
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
writeFile() Writes the the internal file content into the given filename. yii\mongodb\file\ActiveRecord

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
extractFileName() Extracts filename from given raw file value. yii\mongodb\file\ActiveRecord
findByCondition() Finds ActiveRecord instance(s) by the given condition. yii\db\BaseActiveRecord
insertInternal() yii\mongodb\file\ActiveRecord
resolveFields() Determines which fields can be returned by toArray(). yii\base\ArrayableTrait
updateInternal() yii\mongodb\file\ActiveRecord

Events

Hide inherited events

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

Constants

Hide inherited constants

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

Property Details

$fileContent public read-only property

File content.

$fileResource public read-only property

File stream resource.

Method Details

attributes() public method

Returns the list of all attribute names of the model.

This method could be overridden by child classes to define available attributes. Note: all attributes defined in base Active Record class should be always present in returned array. For example:

public function attributes()
{
    return array_merge(
        parent::attributes(),
        ['tags', 'status']
    );
}
public array attributes ( )
return array

List of attribute names.

extractFileName() protected method

Extracts filename from given raw file value.

protected string extractFileName ( $file )
$file mixed

Raw file value.

return string

File name.

throws yii\base\InvalidParamException

on invalid file value.

find() public static method

Creates an \yii\mongodb\file\ActiveQueryInterface instance for query purpose.

The returned \yii\mongodb\file\ActiveQueryInterface instance can be further customized by calling methods defined in \yii\mongodb\file\ActiveQueryInterface before one() or all() is called to return populated ActiveRecord instances. For example,

// find the customer whose ID is 1
$customer = Customer::find()->where(['id' => 1])->one();

// find all active customers and order them by their age:
$customers = Customer::find()
    ->where(['status' => 1])
    ->orderBy('age')
    ->all();

This method is also called by \yii\mongodb\file\BaseActiveRecord::hasOne() and \yii\mongodb\file\BaseActiveRecord::hasMany() to create a relational query.

You may override this method to return a customized query. For example,

class Customer extends ActiveRecord
{
    public static function find()
    {
        // use CustomerQuery instead of the default ActiveQuery
        return new CustomerQuery(get_called_class());
    }
}

The following code shows how to apply a default condition for all queries:

class Customer extends ActiveRecord
{
    public static function find()
    {
        return parent::find()->where(['deleted' => false]);
    }
}

// Use andWhere()/orWhere() to apply the default condition
// SELECT FROM customer WHERE `deleted`=:deleted AND age>30
$customers = Customer::find()->andWhere('age>30')->all();

// Use where() to ignore the default condition
// SELECT FROM customer WHERE age>30
$customers = Customer::find()->where('age>30')->all();


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

The newly created yii\mongodb\file\ActiveQuery instance.

getCollection() public static method

Return the Mongo GridFS collection instance for this AR class.

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

Collection instance.

getFileContent() public method

Returns the associated file content.

public null|string getFileContent ( )
return null|string

File content.

throws yii\base\InvalidParamException

on invalid file attribute value.

getFileResource() public method

This method returns a stream resource that can be used with all file functions in PHP, which deal with reading files. The contents of the file are pulled out of MongoDB on the fly, so that the whole file does not have to be loaded into memory first.

public resource getFileResource ( )
return resource

File stream resource.

throws yii\base\InvalidParamException

on invalid file attribute value.

insertInternal() protected method
protected void insertInternal ( $attributes null )
$attributes
refreshFile() public method

Refreshes the \yii\mongodb\file\file attribute from file collection, using current primary key.

public \MongoGridFSFile|null refreshFile ( )
return \MongoGridFSFile|null

Refreshed file value.

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

Writes the the internal file content into the given filename.

public boolean writeFile ( $filename )
$filename string

Full filename to be written.

return boolean

Whether the operation was successful.

throws yii\base\InvalidParamException

on invalid file attribute value.