Abstract Class yii\sphinx\ActiveRecord

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

ActiveRecord is the base class for classes representing relational data in terms of objects.

Warning: optimistic lock will NOT work in case of updating fields (not attributes) for the runtime indexes!

Public Properties

Hide inherited properties

Property Type Description Defined By
$snippet string Snippet value. yii\sphinx\ActiveRecord
$snippetSource string Snippet source string. yii\sphinx\ActiveRecord

Public Methods

Hide inherited methods

Method Description Defined By
attributes() Returns the list of all attribute names of the model. yii\sphinx\ActiveRecord
callKeywords() Returns tokenized and normalized forms of the keywords, and, optionally, keyword statistics. yii\sphinx\ActiveRecord
callSnippets() Builds a snippet from provided data and query, using specified index settings. yii\sphinx\ActiveRecord
delete() Deletes the index entry corresponding to this active record. yii\sphinx\ActiveRecord
deleteAll() Deletes rows in the index using the provided conditions. yii\sphinx\ActiveRecord
equals() Returns a value indicating whether the given active record is the same as the current one. yii\sphinx\ActiveRecord
find() yii\sphinx\ActiveRecord
findBySql() Creates an yii\sphinx\ActiveQuery instance with a given SQL statement. yii\sphinx\ActiveRecord
getDb() Returns the Sphinx connection used by this AR class. yii\sphinx\ActiveRecord
getIndexSchema() Returns the schema information of the Sphinx index associated with this AR class. yii\sphinx\ActiveRecord
getSnippet() Returns current snippet value or generates new one from given match. yii\sphinx\ActiveRecord
getSnippetSource() Returns the string, which should be used as a source to create snippet for this Active Record instance. yii\sphinx\ActiveRecord
indexName() Declares the name of the Sphinx index associated with this AR class. yii\sphinx\ActiveRecord
insert() Inserts a row into the associated Sphinx index using the attribute values of this record. yii\sphinx\ActiveRecord
isTransactional() Returns a value indicating whether the specified operation is transactional in the current scenario. yii\sphinx\ActiveRecord
populateRecord() yii\sphinx\ActiveRecord
primaryKey() Returns the primary key name for this AR class. yii\sphinx\ActiveRecord
setSnippet() yii\sphinx\ActiveRecord
transactions() Declares which operations should be performed within a transaction in different scenarios. yii\sphinx\ActiveRecord
update() Saves the changes to this active record into the associated Sphinx index. yii\sphinx\ActiveRecord
updateAll() Updates the whole table using the provided attribute values and conditions. yii\sphinx\ActiveRecord

Protected Methods

Hide inherited methods

Method Description Defined By
fetchSnippet() Builds up the snippet value from the given query. yii\sphinx\ActiveRecord
updateInternal() yii\sphinx\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\sphinx\ActiveRecord
OP_DELETE 0x4 The delete operation. This is mainly used when overriding transactions() to specify which operations are transactional. yii\sphinx\ActiveRecord
OP_INSERT 0x1 The insert operation. This is mainly used when overriding transactions() to specify which operations are transactional. yii\sphinx\ActiveRecord
OP_UPDATE 0x2 The update operation. This is mainly used when overriding transactions() to specify which operations are transactional. yii\sphinx\ActiveRecord

Property Details

Hide inherited properties

$snippet public property

Snippet value.

public string $snippet null
$snippetSource public property

Snippet source string. This property is read-only.

public string $snippetSource null

Method Details

Hide inherited methods

attributes() public method

Returns the list of all attribute names of the model.

The default implementation will return all column names of the table associated with this AR class.

public array attributes ( )
return array

List of attribute names.

                public function attributes()
{
    return array_keys(static::getIndexSchema()->columns);
}

            
callKeywords() public static method

Returns tokenized and normalized forms of the keywords, and, optionally, keyword statistics.

public static array callKeywords ( $text, $fetchStatistic false )
$text string

The text to break down to keywords.

$fetchStatistic boolean

Whether to return document and hit occurrence statistics

return array

Keywords and statistics

                public static function callKeywords($text, $fetchStatistic = false)
{
    $command = static::getDb()->createCommand();
    $command->callKeywords(static::indexName(), $text, $fetchStatistic);
    return $command->queryAll();
}

            
callSnippets() public static method

Builds a snippet from provided data and query, using specified index settings.

public static string|array callSnippets ( $source, $match, $options = [] )
$source string|array

Is the source data to extract a snippet from. It could be either a single string or array of strings.

$match string

The full-text query to build snippets for.

$options array

List of options in format: optionName => optionValue

return string|array

Built snippet in case "source" is a string, list of built snippets in case "source" is an array.

                public static function callSnippets($source, $match, $options = [])
{
    $command = static::getDb()->createCommand();
    $command->callSnippets(static::indexName(), $source, $match, $options);
    if (is_array($source)) {
        return $command->queryColumn();
    } else {
        return $command->queryScalar();
    }
}

            
delete() public method

Deletes the index entry corresponding to this active record.

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 record from the index;
  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|false delete ( )
return integer|false

The number of rows deleted, or false if the deletion is unsuccessful for some reason. Note that it is possible the number of rows 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()
{
    $db = static::getDb();
    $transaction = $this->isTransactional(self::OP_DELETE) && $db->getTransaction() === null ? $db->beginTransaction() : null;
    try {
        $result = false;
        if ($this->beforeDelete()) {
            // 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 = $this->deleteAll($condition);
            if ($lock !== null && !$result) {
                throw new StaleObjectException('The object being deleted is outdated.');
            }
            $this->setOldAttributes(null);
            $this->afterDelete();
        }
        if ($transaction !== null) {
            if ($result === false) {
                $transaction->rollBack();
            } else {
                $transaction->commit();
            }
        }
    } catch (\Exception $e) {
        if ($transaction !== null) {
            $transaction->rollBack();
        }
        throw $e;
    }
    return $result;
}

            
deleteAll() public static method

Deletes rows in the index using the provided conditions.

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

Article::deleteAll('status = 3');
public static integer deleteAll ( $condition '', $params = [] )
$condition string|array

The conditions that will be put in the WHERE part of the DELETE SQL. Please refer to Query::where() on how to specify this parameter.

$params array

The parameters (name => value) to be bound to the query.

return integer

The number of rows deleted

                public static function deleteAll($condition = '', $params = [])
{
    $command = static::getDb()->createCommand();
    $command->delete(static::indexName(), $condition, $params);
    return $command->execute();
}

            
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 index 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\sphinx\ActiveRecord

Record to compare to

return boolean

Whether the two active records refer to the same row in the same index.

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

            
fetchSnippet() protected method

Builds up the snippet value from the given query.

protected string fetchSnippet ( $match, $options = [] )
$match string

The full-text query to build snippets for.

$options array

List of options in format: optionName => optionValue

return string

Snippet value.

                protected function fetchSnippet($match, $options = [])
{
    return static::callSnippets($this->getSnippetSource(), $match, $options);
}

            
find() public static method

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

The newly created yii\sphinx\ActiveQuery instance.

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

            
findBySql() public static method

Creates an yii\sphinx\ActiveQuery instance with a given SQL statement.

Note that because the SQL statement is already specified, calling additional query modification methods (such as where(), order()) on the created yii\sphinx\ActiveQuery instance will have no effect. However, calling with(), asArray() or indexBy() is still fine.

Below is an example:

$customers = Article::findBySql("SELECT * FROM `idx_article` WHERE MATCH('development')")->all();
public static yii\sphinx\ActiveQuery findBySql ( $sql, $params = [] )
$sql string

The SQL statement to be executed

$params array

Parameters to be bound to the SQL statement during execution.

return yii\sphinx\ActiveQuery

The newly created yii\sphinx\ActiveQuery instance

                public static function findBySql($sql, $params = [])
{
    $query = static::find();
    $query->sql = $sql;
    return $query->params($params);
}

            
getDb() public static method

Returns the Sphinx connection used by this AR class.

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

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

The Sphinx connection used by this AR class.

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

            
getIndexSchema() public static method

Returns the schema information of the Sphinx index associated with this AR class.

public static yii\sphinx\IndexSchema getIndexSchema ( )
return yii\sphinx\IndexSchema

The schema information of the Sphinx index associated with this AR class.

throws \yii\base\InvalidConfigException

if the index for the AR class does not exist.

                public static function getIndexSchema()
{
    $schema = static::getDb()->getIndexSchema(static::indexName());
    if ($schema !== null) {
        return $schema;
    } else {
        throw new InvalidConfigException("The index does not exist: " . static::indexName());
    }
}

            
getSnippet() public method

Returns current snippet value or generates new one from given match.

public string getSnippet ( $match null, $options = [] )
$match string

Snippet source query

$options array

List of options in format: optionName => optionValue

return string

Snippet value

                public function getSnippet($match = null, $options = [])
{
    if ($match !== null) {
        $this->_snippet = $this->fetchSnippet($match, $options);
    }
    return $this->_snippet;
}

            
getSnippetSource() public method

Returns the string, which should be used as a source to create snippet for this Active Record instance.

Child classes must implement this method to return the actual snippet source text. For example:

public function getSnippetSource()
{
    return $this->snippetSourceRelation->content;
}
public string getSnippetSource ( )
return string

Snippet source string.

throws \yii\base\NotSupportedException

if this is not supported by the Active Record class

                public function getSnippetSource()
{
    throw new NotSupportedException($this->className() . ' does not provide snippet source.');
}

            
indexName() public static method

Declares the name of the Sphinx index associated with this AR class.

By default this method returns the class name as the index name by calling Inflector::camel2id(). For example, 'Article' becomes 'article', and 'StockItem' becomes 'stock_item'. You may override this method if the index is not named after this convention.

public static string indexName ( )
return string

The index name

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

            
insert() public method

Inserts a row into the associated Sphinx index 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 index. 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 changedAttributes will be inserted.

For example, to insert an article record:

$article = new Article();
$article->id = $id;
$article->genre_id = $genreId;
$article->content = $content;
$article->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.

$attributes array

List of attributes that need to be saved. Defaults to null, meaning all attributes that are loaded from index 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;
    }
    $db = static::getDb();
    if ($this->isTransactional(self::OP_INSERT) && $db->getTransaction() === null) {
        $transaction = $db->beginTransaction();
        try {
            $result = $this->insertInternal($attributes);
            if ($result === false) {
                $transaction->rollBack();
            } else {
                $transaction->commit();
            }
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    } else {
        $result = $this->insertInternal($attributes);
    }
    return $result;
}

            
isTransactional() public method

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);
}

            
populateRecord() public static method

public static void populateRecord ( $record, $row )
$record
$row

                public static function populateRecord($record, $row)
{
    $columns = static::getIndexSchema()->columns;
    foreach ($row as $name => $value) {
        if (isset($columns[$name])) {
            if ($columns[$name]->isMva) {
                if (empty($value)) {
                    $row[$name] = [];
                } else {
                    $mvaValue = explode(',', $value);
                    $row[$name] = array_map([$columns[$name], 'phpTypecast'], $mvaValue);
                }
            } else {
                $row[$name] = $columns[$name]->phpTypecast($value);
            }
        }
    }
    parent::populateRecord($record, $row);
}

            
primaryKey() public static method

Returns the primary key name for this AR class.

The default implementation will return the primary key as declared in the Sphinx index, which is associated with this AR class.

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

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

The primary keys of the associated Sphinx index.

                public static function primaryKey()
{
    return [static::getIndexSchema()->primaryKey];
}

            
setSnippet() public method

public void setSnippet ( $snippet )
$snippet string

                public function setSnippet($snippet)
{
    $this->_snippet = $snippet;
}

            
transactions() public method

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

Saves the changes to this active record into the associated Sphinx index.

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. save the record into index. 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_UPDATE, EVENT_AFTER_UPDATE and EVENT_AFTER_VALIDATE will be raised by the corresponding methods.

Only the changedAttributes will be saved into database.

For example, to update an article record:

$article = Article::findOne($id);
$article->genre_id = $genreId;
$article->group_id = $groupId;
$article->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 ($this->update() !== false) {
    // update successful
} else {
    // update failed
}
public integer|false update ( $runValidation true, $attributeNames null )
$runValidation boolean

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

$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

in case update failed.

                public function update($runValidation = true, $attributeNames = null)
{
    if ($runValidation && !$this->validate($attributeNames)) {
        return false;
    }
    $db = static::getDb();
    if ($this->isTransactional(self::OP_UPDATE) && $db->getTransaction() === null) {
        $transaction = $db->beginTransaction();
        try {
            $result = $this->updateInternal($attributeNames);
            if ($result === false) {
                $transaction->rollBack();
            } else {
                $transaction->commit();
            }
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    } else {
        $result = $this->updateInternal($attributeNames);
    }
    return $result;
}

            
updateAll() public static method

Updates the whole table using the provided attribute values and conditions.

For example, to change the status to be 1 for all articles which status is 2:

Article::updateAll(['status' => 1], 'status = 2');
public static integer updateAll ( $attributes, $condition '', $params = [] )
$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 Query::where() on how to specify this parameter.

$params array

The parameters (name => value) to be bound to the query.

return integer

The number of rows updated

                public static function updateAll($attributes, $condition = '', $params = [])
{
    $command = static::getDb()->createCommand();
    $command->update(static::indexName(), $attributes, $condition, $params);
    return $command->execute();
}

            
updateInternal() protected method

See also \yii\sphinx\CActiveRecord::update().

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;
    }
    // Replace is supported only by runtime indexes and necessary only for field update
    $useReplace = false;
    $indexSchema = $this->getIndexSchema();
    if ($this->getIndexSchema()->isRt) {
        foreach ($values as $name => $value) {
            $columnSchema = $indexSchema->getColumn($name);
            if ($columnSchema->isField) {
                $useReplace = true;
                break;
            }
        }
    }
    if ($useReplace) {
        $values = array_merge(
            $this->getAttributes(),
            $values,
            $this->getOldPrimaryKey(true)
        );
        $command = static::getDb()->createCommand();
        $command->replace(static::indexName(), $values);
        // We do not check the return value of replace because it's possible
        // that the REPLACE statement doesn't change anything and thus returns 0.
        $rows = $command->execute();
    } 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 updateAll() because it's possible
        // that the UPDATE statement doesn't change anything and thus returns 0.
        $rows = $this->updateAll($values, $condition);
        if ($lock !== null && !$rows) {
            throw new StaleObjectException('The object being updated is outdated.');
        }
        if (isset($values[$lock])) {
            $this->$lock = $values[$lock];
        }
    }
    $changedAttributes = [];
    foreach ($values as $name => $value) {
        $changedAttributes[$name] = $this->getOldAttribute($name);
        $this->setOldAttribute($name, $value);
    }
    $this->afterSave(false, $changedAttributes);
    return $rows;
}