You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
353 lines
12 KiB
353 lines
12 KiB
11 years ago
|
<?php
|
||
|
/**
|
||
|
* @link http://www.yiiframework.com/
|
||
|
* @copyright Copyright (c) 2008 Yii Software LLC
|
||
|
* @license http://www.yiiframework.com/license/
|
||
|
*/
|
||
|
|
||
11 years ago
|
namespace yii\mongodb;
|
||
11 years ago
|
|
||
|
use yii\base\InvalidConfigException;
|
||
|
use yii\base\InvalidParamException;
|
||
11 years ago
|
use yii\db\BaseActiveRecord;
|
||
11 years ago
|
use yii\base\UnknownMethodException;
|
||
|
use yii\db\StaleObjectException;
|
||
|
use yii\helpers\Inflector;
|
||
|
use yii\helpers\StringHelper;
|
||
|
|
||
|
/**
|
||
11 years ago
|
* ActiveRecord is the base class for classes representing Mongo documents in terms of objects.
|
||
11 years ago
|
*
|
||
|
* @author Paul Klimov <klimov.paul@gmail.com>
|
||
|
* @since 2.0
|
||
|
*/
|
||
11 years ago
|
abstract class ActiveRecord extends BaseActiveRecord
|
||
11 years ago
|
{
|
||
|
/**
|
||
11 years ago
|
* Returns the Mongo connection used by this AR class.
|
||
11 years ago
|
* By default, the "mongodb" application component is used as the Mongo connection.
|
||
11 years ago
|
* You may override this method if you want to use a different database connection.
|
||
|
* @return Connection the database connection used by this AR class.
|
||
|
*/
|
||
|
public static function getDb()
|
||
|
{
|
||
11 years ago
|
return \Yii::$app->getComponent('mongodb');
|
||
11 years ago
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* Updates all documents in the collection using the provided attribute values and conditions.
|
||
11 years ago
|
* For example, to change the status to be 1 for all customers whose status is 2:
|
||
|
*
|
||
|
* ~~~
|
||
|
* Customer::updateAll(['status' => 1], ['status' = 2]);
|
||
|
* ~~~
|
||
|
*
|
||
11 years ago
|
* @param array $attributes attribute values (name-value pairs) to be saved into the collection
|
||
|
* @param array $condition description of the objects to update.
|
||
11 years ago
|
* Please refer to [[Query::where()]] on how to specify this parameter.
|
||
|
* @param array $options list of options in format: optionName => optionValue.
|
||
11 years ago
|
* @return integer the number of documents updated.
|
||
11 years ago
|
*/
|
||
|
public static function updateAll($attributes, $condition = [], $options = [])
|
||
|
{
|
||
|
return static::getCollection()->update($condition, $attributes, $options);
|
||
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* Updates all documents in the collection using the provided counter changes and conditions.
|
||
11 years ago
|
* For example, to increment all customers' age by 1,
|
||
|
*
|
||
|
* ~~~
|
||
|
* Customer::updateAllCounters(['age' => 1]);
|
||
|
* ~~~
|
||
|
*
|
||
|
* @param array $counters the counters to be updated (attribute name => increment value).
|
||
|
* Use negative values if you want to decrement the counters.
|
||
11 years ago
|
* @param array $condition description of the objects to update.
|
||
11 years ago
|
* Please refer to [[Query::where()]] on how to specify this parameter.
|
||
|
* @param array $options list of options in format: optionName => optionValue.
|
||
11 years ago
|
* @return integer the number of documents updated.
|
||
11 years ago
|
*/
|
||
|
public static function updateAllCounters($counters, $condition = [], $options = [])
|
||
|
{
|
||
11 years ago
|
return static::getCollection()->update($condition, ['$inc' => $counters], $options);
|
||
11 years ago
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* 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.
|
||
11 years ago
|
*
|
||
|
* For example, to delete all customers whose status is 3:
|
||
|
*
|
||
|
* ~~~
|
||
|
* Customer::deleteAll('status = 3');
|
||
|
* ~~~
|
||
|
*
|
||
11 years ago
|
* @param array $condition description of the objects to delete.
|
||
11 years ago
|
* Please refer to [[Query::where()]] on how to specify this parameter.
|
||
|
* @param array $options list of options in format: optionName => optionValue.
|
||
11 years ago
|
* @return integer the number of documents deleted.
|
||
11 years ago
|
*/
|
||
|
public static function deleteAll($condition = [], $options = [])
|
||
|
{
|
||
|
$options['w'] = 1;
|
||
|
if (!array_key_exists('multiple', $options)) {
|
||
|
$options['multiple'] = true;
|
||
|
}
|
||
|
return static::getCollection()->remove($condition, $options);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Creates an [[ActiveQuery]] instance.
|
||
11 years ago
|
* This method is called by [[find()]] to start a "find" command.
|
||
11 years ago
|
* You may override this method to return a customized query (e.g. `CustomerQuery` specified
|
||
|
* written for querying `Customer` purpose.)
|
||
|
* @return ActiveQuery the newly created [[ActiveQuery]] instance.
|
||
|
*/
|
||
|
public static function createQuery()
|
||
|
{
|
||
|
return new ActiveQuery(['modelClass' => get_called_class()]);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 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 table is not named after this convention.
|
||
11 years ago
|
* @return string|array the collection name
|
||
11 years ago
|
*/
|
||
|
public static function collectionName()
|
||
|
{
|
||
|
return Inflector::camel2id(StringHelper::basename(get_called_class()), '_');
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Return the Mongo collection instance for this AR class.
|
||
|
* @return Collection collection instance.
|
||
|
*/
|
||
|
public static function getCollection()
|
||
|
{
|
||
|
return static::getDb()->getCollection(static::collectionName());
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Returns the primary key name(s) for this AR class.
|
||
|
* The default implementation will return ['_id'].
|
||
|
*
|
||
11 years ago
|
* Note that an array should be returned even for a collection with single primary key.
|
||
11 years ago
|
*
|
||
11 years ago
|
* @return string[] the primary keys of the associated Mongo collection.
|
||
11 years ago
|
*/
|
||
|
public static function primaryKey()
|
||
|
{
|
||
|
return ['_id'];
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Creates an [[ActiveRelation]] instance.
|
||
|
* This method is called by [[hasOne()]] and [[hasMany()]] to create a relation instance.
|
||
|
* You may override this method to return a customized relation.
|
||
|
* @param array $config the configuration passed to the ActiveRelation class.
|
||
|
* @return ActiveRelation the newly created [[ActiveRelation]] instance.
|
||
|
*/
|
||
|
public static function createActiveRelation($config = [])
|
||
|
{
|
||
|
return new ActiveRelation($config);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Returns the list of all attribute names of the model.
|
||
11 years ago
|
* 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'];
|
||
|
* }
|
||
|
* ~~~
|
||
11 years ago
|
* @return array list of attribute names.
|
||
|
*/
|
||
|
public function attributes()
|
||
|
{
|
||
11 years ago
|
throw new InvalidConfigException('The attributes() method of mongodb ActiveRecord has to be implemented by child classes.');
|
||
11 years ago
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* Inserts a row into the associated Mongo collection using the attribute values of this record.
|
||
11 years ago
|
*
|
||
|
* 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;
|
||
11 years ago
|
* 4. insert the record into collection. If this fails, it will skip the rest of the steps;
|
||
11 years ago
|
* 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|changed attribute values]] will be inserted into database.
|
||
|
*
|
||
11 years ago
|
* If the primary key is null during insertion, it will be populated with the actual
|
||
|
* value after insertion.
|
||
11 years ago
|
*
|
||
|
* For example, to insert a customer record:
|
||
|
*
|
||
|
* ~~~
|
||
|
* $customer = new Customer;
|
||
|
* $customer->name = $name;
|
||
|
* $customer->email = $email;
|
||
|
* $customer->insert();
|
||
|
* ~~~
|
||
|
*
|
||
|
* @param boolean $runValidation whether to perform validation before saving the record.
|
||
11 years ago
|
* If the validation fails, the record will not be inserted into the collection.
|
||
11 years ago
|
* @param array $attributes list of attributes that need to be saved. Defaults to null,
|
||
11 years ago
|
* meaning all attributes that are loaded will be saved.
|
||
11 years ago
|
* @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;
|
||
|
}
|
||
|
$result = $this->insertInternal($attributes);
|
||
|
return $result;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @see ActiveRecord::insert()
|
||
|
*/
|
||
11 years ago
|
protected function insertInternal($attributes = null)
|
||
11 years ago
|
{
|
||
|
if (!$this->beforeSave(true)) {
|
||
|
return false;
|
||
|
}
|
||
|
$values = $this->getDirtyAttributes($attributes);
|
||
|
if (empty($values)) {
|
||
11 years ago
|
$currentAttributes = $this->getAttributes();
|
||
11 years ago
|
foreach ($this->primaryKey() as $key) {
|
||
11 years ago
|
$values[$key] = isset($currentAttributes[$key]) ? $currentAttributes[$key] : null;
|
||
11 years ago
|
}
|
||
|
}
|
||
|
$collection = static::getCollection();
|
||
|
$newId = $collection->insert($values);
|
||
|
$this->setAttribute('_id', $newId);
|
||
|
foreach ($values as $name => $value) {
|
||
11 years ago
|
$this->setOldAttribute($name, $value);
|
||
11 years ago
|
}
|
||
|
$this->afterSave(true);
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* @see ActiveRecord::update()
|
||
11 years ago
|
* @throws StaleObjectException
|
||
|
*/
|
||
11 years ago
|
protected function updateInternal($attributes = null)
|
||
11 years ago
|
{
|
||
|
if (!$this->beforeSave(false)) {
|
||
|
return false;
|
||
|
}
|
||
|
$values = $this->getDirtyAttributes($attributes);
|
||
|
if (empty($values)) {
|
||
|
$this->afterSave(false);
|
||
|
return 0;
|
||
|
}
|
||
|
$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.
|
||
11 years ago
|
$rows = static::getCollection()->update($condition, $values);
|
||
11 years ago
|
|
||
|
if ($lock !== null && !$rows) {
|
||
|
throw new StaleObjectException('The object being updated is outdated.');
|
||
|
}
|
||
|
|
||
|
foreach ($values as $name => $value) {
|
||
11 years ago
|
$this->setOldAttribute($name, $this->getAttribute($name));
|
||
11 years ago
|
}
|
||
|
$this->afterSave(false);
|
||
|
return $rows;
|
||
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* Deletes the document corresponding to this active record from the collection.
|
||
11 years ago
|
*
|
||
|
* This method performs the following steps in order:
|
||
|
*
|
||
|
* 1. call [[beforeDelete()]]. If the method returns false, it will skip the
|
||
|
* rest of the steps;
|
||
11 years ago
|
* 2. delete the document from the collection;
|
||
11 years ago
|
* 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.
|
||
|
*
|
||
11 years ago
|
* @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.
|
||
11 years ago
|
* @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
|
||
|
* being deleted is outdated.
|
||
|
* @throws \Exception in case delete failed.
|
||
|
*/
|
||
|
public function delete()
|
||
|
{
|
||
|
$result = false;
|
||
|
if ($this->beforeDelete()) {
|
||
11 years ago
|
$result = $this->deleteInternal();
|
||
11 years ago
|
$this->afterDelete();
|
||
|
}
|
||
|
return $result;
|
||
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* @see ActiveRecord::delete()
|
||
|
* @throws StaleObjectException
|
||
|
*/
|
||
|
protected function deleteInternal()
|
||
|
{
|
||
|
// 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);
|
||
|
return $result;
|
||
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* 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 [[isNewRecord|is new]] they are also considered not equal.
|
||
|
* @param ActiveRecord $record record to compare to
|
||
11 years ago
|
* @return boolean whether the two active records refer to the same row in the same Mongo collection.
|
||
11 years ago
|
*/
|
||
|
public function equals($record)
|
||
|
{
|
||
|
if ($this->isNewRecord || $record->isNewRecord) {
|
||
|
return false;
|
||
|
}
|
||
11 years ago
|
return $this->collectionName() === $record->collectionName() && (string)$this->getPrimaryKey() === (string)$record->getPrimaryKey();
|
||
11 years ago
|
}
|
||
|
}
|