Abstract Class yii\mongodb\file\ActiveRecord

Inheritanceyii\mongodb\file\ActiveRecord » yii\mongodb\ActiveRecord » yii\db\BaseActiveRecord
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-mongodb/blob/master/src/file/ActiveRecord.php

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

To specify source file use the 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 newFileContent attribute:

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

Note: newFileContent always takes precedence over file.

Public Properties

Hide inherited properties

Property Type Description Defined By
$fileContent null|string File content. yii\mongodb\file\ActiveRecord
$fileResource resource File stream resource. yii\mongodb\file\ActiveRecord

Public Methods

Hide inherited methods

Method Description Defined By
LockDocument() Locks a document of the collection in a transaction (like select for update feature in MySQL) yii\mongodb\ActiveRecord
LockDocumentStubbornly() Locking a document in stubborn mode on a transaction (like select for update feature in MySQL) yii\mongodb\ActiveRecord
attributes() Returns the list of all attribute names of the model. yii\mongodb\file\ActiveRecord
collectionName() Declares the name of the Mongo collection associated with this AR class. yii\mongodb\ActiveRecord
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
equals() Returns a value indicating whether the given active record is the same as the current one. yii\mongodb\ActiveRecord
find() yii\mongodb\file\ActiveRecord
getCollection() Return the Mongo GridFS collection instance for this AR class. yii\mongodb\file\ActiveRecord
getDb() Returns the Mongo connection used by this AR class. yii\mongodb\ActiveRecord
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
insert() Inserts a row into the associated Mongo collection using the attribute values of this record. yii\mongodb\ActiveRecord
isTransactional() Returns a value indicating whether the specified operation is transactional in the current $scenario. yii\mongodb\ActiveRecord
primaryKey() Returns the primary key name(s) for this AR class. yii\mongodb\ActiveRecord
refreshFile() Refreshes the file attribute from file collection, using current primary key. yii\mongodb\file\ActiveRecord
toArray() yii\mongodb\ActiveRecord
transactions() Declares which DB operations should be performed within a transaction in different scenarios. yii\mongodb\ActiveRecord
update() Saves the changes to this active record into the associated database table. yii\mongodb\ActiveRecord
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
writeFile() Writes the the internal file content into the given filename. yii\mongodb\file\ActiveRecord

Constants

Hide inherited constants

Constant Value Description Defined By
OP_ALL 0x7 All three operations: insert, update, delete. This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE. yii\mongodb\ActiveRecord
OP_DELETE 0x4 The delete operation. This is mainly used when overriding transactions() to specify which operations are transactional. yii\mongodb\ActiveRecord
OP_INSERT 0x1 The insert operation. This is mainly used when overriding transactions() to specify which operations are transactional. yii\mongodb\ActiveRecord
OP_UPDATE 0x2 The update operation. This is mainly used when overriding transactions() to specify which operations are transactional. yii\mongodb\ActiveRecord

Property Details

Hide inherited properties

$fileContent public property

File content. This property is read-only.

public null|string $fileContent null
$fileResource public property

File stream resource. This property is read-only.

public resource $fileResource null

Method Details

Hide inherited methods

LockDocument() public static method

Defined in: yii\mongodb\ActiveRecord::LockDocument()

Locks a document of the collection in a transaction (like select for update feature in MySQL)

See also https://www.mongodb.com/blog/post/how-to-select--for-update-inside-mongodb-transactions.

public static yii\mongodb\ActiveRecord|null LockDocument ( $id, $lockFieldName, $modifyOptions = [], $db null )
$id mixed

A document id (primary key > _id)

$lockFieldName string

The name of the field you want to lock.

$modifyOptions array

List of the options in format: optionName => optionValue.

$db yii\mongodb\Connection

The Mongo connection uses it to execute the query.

return yii\mongodb\ActiveRecord|null

The locked document. Returns instance of ActiveRecord. Null will be returned if the query does not have a result.

                public static function LockDocument($id, $lockFieldName, $modifyOptions = [], $db = null)
{
    $db = $db ? $db : static::getDb();
    $db->transactionReady('lock document');
    $options['new'] = true;
    return static::find()
        ->where(['_id' => $id])
        ->modify(
            [
                '$set' =>[$lockFieldName => new ObjectId]
            ],
            $modifyOptions,
            $db
        )
    ;
}

            
LockDocumentStubbornly() public static method

Defined in: yii\mongodb\ActiveRecord::LockDocumentStubbornly()

Locking a document in stubborn mode on a transaction (like select for update feature in MySQL)

See also https://www.mongodb.com/blog/post/how-to-select--for-update-inside-mongodb-transactions notice : you can not use stubborn mode if transaction is started in current session (or use your session with mySession parameter).

public static yii\mongodb\ActiveRecord|null LockDocumentStubbornly ( $id, $lockFieldName, $options = [], $db null )
$id mixed

A document id (primary key > _id)

$lockFieldName
$options array

List of options in format: [ 'mySession' => false, # A custom session instance of ClientSession for start a transaction. 'transactionOptions' => [], # New transaction options. see $transactionOptions in Transaction::start() 'modifyOptions' => [], # See $options in ActiveQuery::modify() 'sleep' => 1000000, # A time parameter in microseconds to wait. the default is one second. 'try' => 0, # Maximum count of retry. throw write conflict error after reached this value. the zero default is unlimited. 'lockFieldName' => '_lock' # The name of the field you want to lock. default is '_lock' ]

$db yii\mongodb\Connection

The Mongo connection uses it to execute the query.

return yii\mongodb\ActiveRecord|null

Returns the locked document. Returns instance of ActiveRecord. Null will be returned if the query does not have a result. When the total number of attempts to lock the document passes try, conflict error will be thrown

                public static function LockDocumentStubbornly($id, $lockFieldName, $options = [], $db = null)
{
    $db = $db ? $db : static::getDb();
    $options = array_replace_recursive(
        [
            'mySession' => false,
            'transactionOptions' => [],
            'modifyOptions' => [],
            'sleep' => 1000000,
            'try' => 0,
        ],
        $options
    );
    $options['modifyOptions']['new'] = true;
    $session = $options['mySession'] ? $options['mySession'] : $db->startSessionOnce(); 
    if ($session->getInTransaction()) {
        throw new Exception('You can\'t use stubborn lock feature because current connection is in a transaction.');
    }
    // start stubborn
    $tiredCounter = 0;
    StartStubborn:
    $session->transaction->start($options['transactionOptions']);
    try {
        $doc = static::find()
            ->where(['_id' => $id])
            ->modify(
                [
                    '$set' => [
                        $lockFieldName => new ObjectId
                    ]
                ],
                $options['modifyOptions'],
                $db
            );
        return $doc;
    } catch(\Exception $e) {
        $session->transaction->rollBack();
        $tiredCounter++;
        if ($options['try'] !== 0 && $tiredCounter === $options['try']) {
            throw $e;
        }
        usleep($options['sleep']);
        goto StartStubborn;
    }
}

            
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.

                public function attributes()
{
    return [
        '_id',
        'filename',
        'uploadDate',
        'length',
        'chunkSize',
        'md5',
        'file',
        'newFileContent'
    ];
}

            
collectionName() public static method

Defined in: yii\mongodb\ActiveRecord::collectionName()

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

                public static function collectionName()
{
    return Inflector::camel2id(StringHelper::basename(get_called_class()), '_');
}

            
delete() public method

Defined in: yii\mongodb\ActiveRecord::delete()

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 optimisticLock is enabled and the data being deleted is outdated.

throws Exception

in case delete failed.

                public function delete()
{
    if (!$this->isTransactional(self::OP_DELETE)) {
        return $this->deleteInternal();
    }
    $result = null;
    static::getDb()->transaction(function() use (&$result) {
        $result = $this->deleteInternal();
    });
    return $result;
}

            
deleteAll() public static method

Defined in: yii\mongodb\ActiveRecord::deleteAll()

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 Query::where() on how to specify this parameter.

$options array

List of options in format: optionName => optionValue.

return integer

The number of documents deleted.

                public static function deleteAll($condition = [], $options = [])
{
    return static::getCollection()->remove($condition, $options);
}

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

                protected function deleteInternal()
{
    if (!$this->beforeDelete()) {
        return false;
    }
    // we do not check the return value of deleteAll() because it's possible
    // the record is already deleted in the database and thus the method will return 0
    $condition = $this->getOldPrimaryKey(true);
    $lock = $this->optimisticLock();
    if ($lock !== null) {
        $condition[$lock] = $this->$lock;
    }
    $result = static::getCollection()->remove($condition);
    if ($lock !== null && !$result) {
        throw new StaleObjectException('The object being deleted is outdated.');
    }
    $this->setOldAttributes(null);
    $this->afterDelete();
    return $result;
}

            
equals() public method

Defined in: yii\mongodb\ActiveRecord::equals()

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

                public function equals($record)
{
    if ($this->isNewRecord || $record->isNewRecord) {
        return false;
    }
    return $this->collectionName() === $record->collectionName() && (string) $this->getPrimaryKey() === (string) $record->getPrimaryKey();
}

            
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.

                protected function extractFileName($file)
{
    if ($file instanceof UploadedFile) {
        return $file->tempName;
    } elseif (is_string($file)) {
        if (file_exists($file)) {
            return $file;
        }
        throw new InvalidParamException("File '{$file}' does not exist.");
    }
    throw new InvalidParamException('Unsupported type of "file" attribute.');
}

            
find() public static method

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

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

                public static function find()
{
    return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
}

            
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.

                public static function getCollection()
{
    return static::getDb()->getFileCollection(static::collectionName());
}

            
getDb() public static method

Defined in: yii\mongodb\ActiveRecord::getDb()

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.

                public static function getDb()
{
    return Yii::$app->get('mongodb');
}

            
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.

                public function getFileContent()
{
    $file = $this->getAttribute('file');
    if (empty($file) && !$this->getIsNewRecord()) {
        $file = $this->refreshFile();
    }
    if (empty($file)) {
        return null;
    } elseif ($file instanceof Download) {
        $fileSize = $file->getSize();
        return empty($fileSize) ? null : $file->toString();
    } elseif ($file instanceof UploadedFile) {
        return file_get_contents($file->tempName);
    } elseif (is_string($file)) {
        if (file_exists($file)) {
            return file_get_contents($file);
        }
        throw new InvalidParamException("File '{$file}' does not exist.");
    }
    throw new InvalidParamException('Unsupported type of "file" attribute.');
}

            
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.

                public function getFileResource()
{
    $file = $this->getAttribute('file');
    if (empty($file) && !$this->getIsNewRecord()) {
        $file = $this->refreshFile();
    }
    if (empty($file)) {
        throw new InvalidParamException('There is no file associated with this object.');
    } elseif ($file instanceof Download) {
        return $file->getResource();
    } elseif ($file instanceof UploadedFile) {
        return fopen($file->tempName, 'r');
    } elseif (is_string($file)) {
        if (file_exists($file)) {
            return fopen($file, 'r');
        }
        throw new InvalidParamException("File '{$file}' does not exist.");
    }
    throw new InvalidParamException('Unsupported type of "file" attribute.');
}

            
insert() public method

Defined in: yii\mongodb\ActiveRecord::insert()

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

                public function insert($runValidation = true, $attributes = null)
{
    if ($runValidation && !$this->validate($attributes)) {
        return false;
    }
    if (!$this->isTransactional(self::OP_INSERT)) {
        return $this->insertInternal($attributes);
    }
    $result = null;
    static::getDb()->transaction(function() use ($attributes, &$result) {
        $result = $this->insertInternal($attributes);
    });
    return $result;
}

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

                protected function insertInternal($attributes = null)
{
    if (!$this->beforeSave(true)) {
        return false;
    }
    $values = $this->getDirtyAttributes($attributes);
    if (empty($values)) {
        $currentAttributes = $this->getAttributes();
        foreach ($this->primaryKey() as $key) {
            $values[$key] = isset($currentAttributes[$key]) ? $currentAttributes[$key] : null;
        }
    }
    $collection = static::getCollection();
    if (isset($values['newFileContent'])) {
        $newFileContent = $values['newFileContent'];
        unset($values['newFileContent']);
    }
    if (isset($values['file'])) {
        $newFile = $values['file'];
        unset($values['file']);
    }
    if (isset($newFileContent)) {
        $newId = $collection->insertFileContent($newFileContent, $values);
    } elseif (isset($newFile)) {
        $fileName = $this->extractFileName($newFile);
        $newId = $collection->insertFile($fileName, $values);
    } else {
        $newId = $collection->insert($values);
    }
    if ($newId !== null) {
        $this->setAttribute('_id', $newId);
        $values['_id'] = $newId;
    }
    $changedAttributes = array_fill_keys(array_keys($values), null);
    $this->setOldAttributes($values);
    $this->afterSave(true, $changedAttributes);
    return true;
}

            
isTransactional() public method

Defined in: yii\mongodb\ActiveRecord::isTransactional()

Returns a value indicating whether the specified operation is transactional in the current $scenario.

public boolean isTransactional ( $operation )
$operation integer

The operation to check. Possible values are OP_INSERT, OP_UPDATE and OP_DELETE.

return boolean

Whether the specified operation is transactional in the current scenario.

                public function isTransactional($operation)
{
    $scenario = $this->getScenario();
    $transactions = $this->transactions();
    return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
}

            
primaryKey() public static method

Defined in: yii\mongodb\ActiveRecord::primaryKey()

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.

                public static function primaryKey()
{
    return ['_id'];
}

            
refreshFile() public method

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

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

Refreshed file value.

                public function refreshFile()
{
    $mongoFile = $this->getCollection()->get($this->getPrimaryKey());
    $this->setAttribute('file', $mongoFile);
    return $mongoFile;
}

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

                public function toArray(array $fields = [], array $expand = [], $recursive = true)
{
    $data = parent::toArray($fields, $expand, false);
    if (!$recursive) {
        return $data;
    }
    return $this->toArrayInternal($data);
}

            
transactions() public method

Defined in: yii\mongodb\ActiveRecord::transactions()

Declares which DB operations should be performed within a transaction in different scenarios.

The supported DB operations are: OP_INSERT, OP_UPDATE and OP_DELETE, which correspond to the insert(), update() and delete() methods, respectively. By default, these methods are NOT enclosed in a DB transaction.

In some scenarios, to ensure data consistency, you may want to enclose some or all of them in transactions. You can do so by overriding this method and returning the operations that need to be transactional. For example,

return [
    'admin' => self::OP_INSERT,
    'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
    // the above is equivalent to the following:
    // 'api' => self::OP_ALL,

];

The above declaration specifies that in the "admin" scenario, the insert operation (insert()) should be done in a transaction; and in the "api" scenario, all the operations should be done in a transaction.

public array transactions ( )
return array

The declarations of transactional operations. The array keys are scenarios names, and the array values are the corresponding transaction operations.

                public function transactions()
{
    return [];
}

            
update() public method

Defined in: yii\mongodb\ActiveRecord::update()

Saves the changes to this active record into the associated database table.

This method performs the following steps in order:

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

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

Only the dirtyAttributes will be saved into database.

For example, to update a customer record:

$customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->update();

Note that it is possible the update does not affect any row in the table. In this case, this method will return 0. For this reason, you should use the following code to check if update() is successful or not:

if ($customer->update() !== false) {
    // update successful
} else {
    // update failed
}
public integer|false update ( $runValidation true, $attributeNames null )
$runValidation boolean

Whether to perform validation (calling validate()) before saving the record. Defaults to true. If the validation fails, the record will not be saved to the database and this method will return false.

$attributeNames array

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

return integer|false

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

throws \yii\db\StaleObjectException

if optimisticLock is enabled and the data being updated is outdated.

throws \Exception\Throwable

in case update failed.

                public function update($runValidation = true, $attributeNames = null)
{
    if ($runValidation && !$this->validate($attributeNames)) {
        Yii::info('Model not updated due to validation error.', __METHOD__);
        return false;
    }
    if (!$this->isTransactional(self::OP_UPDATE)) {
        return $this->updateInternal($attributeNames);
    }
    $result = null;
    static::getDb()->transaction(function() use ($attributeNames, &$result) {
        $result = $this->updateInternal($attributeNames);
    });
    return $result;
}

            
updateAll() public static method

Defined in: yii\mongodb\ActiveRecord::updateAll()

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 Query::where() on how to specify this parameter.

$options array

List of options in format: optionName => optionValue.

return integer

The number of documents updated.

                public static function updateAll($attributes, $condition = [], $options = [])
{
    return static::getCollection()->update($condition, $attributes, $options);
}

            
updateAllCounters() public static method

Defined in: yii\mongodb\ActiveRecord::updateAllCounters()

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 Query::where() on how to specify this parameter.

$options array

List of options in format: optionName => optionValue.

return integer

The number of documents updated.

                public static function updateAllCounters($counters, $condition = [], $options = [])
{
    return static::getCollection()->update($condition, ['$inc' => $counters], $options);
}

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

                protected function updateInternal($attributes = null)
{
    if (!$this->beforeSave(false)) {
        return false;
    }
    $values = $this->getDirtyAttributes($attributes);
    if (empty($values)) {
        $this->afterSave(false, $values);
        return 0;
    }
    $collection = static::getCollection();
    if (isset($values['newFileContent'])) {
        $newFileContent = $values['newFileContent'];
        unset($values['newFileContent']);
    }
    if (isset($values['file'])) {
        $newFile = $values['file'];
        unset($values['file']);
    }
    if (isset($newFileContent) || isset($newFile)) {
        $fileAssociatedAttributeNames = [
            'filename',
            'uploadDate',
            'length',
            'chunkSize',
            'md5',
            'file',
            'newFileContent'
        ];
        $values = array_merge($this->getAttributes(null, $fileAssociatedAttributeNames), $values);
        $rows = $this->deleteInternal();
        $insertValues = $values;
        $insertValues['_id'] = $this->getAttribute('_id');
        if (isset($newFileContent)) {
            $collection->insertFileContent($newFileContent, $insertValues);
        } else {
            $fileName = $this->extractFileName($newFile);
            $collection->insertFile($fileName, $insertValues);
        }
        $this->setAttribute('newFileContent', null);
        $this->setAttribute('file', null);
    } else {
        $condition = $this->getOldPrimaryKey(true);
        $lock = $this->optimisticLock();
        if ($lock !== null) {
            if (!isset($values[$lock])) {
                $values[$lock] = $this->$lock + 1;
            }
            $condition[$lock] = $this->$lock;
        }
        // We do not check the return value of update() because it's possible
        // that it doesn't change anything and thus returns 0.
        $rows = $collection->update($condition, $values);
        if ($lock !== null && !$rows) {
            throw new StaleObjectException('The object being updated is outdated.');
        }
    }
    $changedAttributes = [];
    foreach ($values as $name => $value) {
        $changedAttributes[$name] = $this->getOldAttribute($name);
        $this->setOldAttribute($name, $value);
    }
    $this->afterSave(false, $changedAttributes);
    return $rows;
}

            
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.

                public function writeFile($filename)
{
    $file = $this->getAttribute('file');
    if (empty($file) && !$this->getIsNewRecord()) {
        $file = $this->refreshFile();
    }
    if (empty($file)) {
        throw new InvalidParamException('There is no file associated with this object.');
    } elseif ($file instanceof Download) {
        return ($file->toFile($filename) == $file->getSize());
    } elseif ($file instanceof UploadedFile) {
        return copy($file->tempName, $filename);
    } elseif (is_string($file)) {
        if (file_exists($file)) {
            return copy($file, $filename);
        }
        throw new InvalidParamException("File '{$file}' does not exist.");
    }
    throw new InvalidParamException('Unsupported type of "file" attribute.');
}