Inheritance | yii\elasticsearch\ActiveRecord » yii\db\BaseActiveRecord » yii\base\Model » yii\base\Component » yii\base\Object |
---|---|
Implements | ArrayAccess, IteratorAggregate, yii\base\Arrayable, yii\base\Configurable, yii\db\ActiveRecordInterface |
Uses Traits | yii\base\ArrayableTrait |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2-elasticsearch/blob/master/ActiveRecord.php |
ActiveRecord is the base class for classes representing relational data in terms of objects.
This class implements the ActiveRecord pattern for the fulltext search and data storage elasticsearch.
For defining a record a subclass should at least implement the attributes() method to define attributes. The primary key (the _id
field in elasticsearch terms) is represented by getId()
and setId()
. The primary key is not part of the attributes.
The following is an example model called Customer
:
class Customer extends \yii\elasticsearch\ActiveRecord { public function attributes() { return ['id', 'name', 'address', 'registration_date']; } }
You may override index() and type() to define the index and type this record represents.
Property | Type | Description | Defined 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 |
$explanation | array|null | An explanation for each hit on how its score was computed. | yii\elasticsearch\ActiveRecord |
$firstErrors | array | The first errors. | yii\base\Model |
$highlight | array|null | A list of arrays with highlighted excerpts indexed by field names. | yii\elasticsearch\ActiveRecord |
$isNewRecord | boolean | Whether the record is new and should be inserted when calling save(). | yii\db\BaseActiveRecord |
$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\elasticsearch\ActiveRecord |
$primaryKey | mixed | The primary key value. | yii\elasticsearch\ActiveRecord |
$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 |
$score | float | Returns the score of this record when it was retrieved via a find() query. | yii\elasticsearch\ActiveRecord |
$validators | ArrayObject|yii\validators\Validator[] | All the validators declared in the model. | yii\base\Model |
Method | Description | Defined 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 |
arrayAttributes() | A list of attributes that should be treated as array valued when retrieved through yii\elasticsearch\ActiveQuery::fields(). | yii\elasticsearch\ActiveRecord |
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\elasticsearch\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 |
createValidators() | Creates validator objects based on the validation rules specified in rules(). | yii\base\Model |
delete() | Deletes the table row corresponding to this active record. | yii\elasticsearch\ActiveRecord |
deleteAll() | Deletes rows in the table using the provided conditions. | yii\elasticsearch\ActiveRecord |
detachBehavior() | Detaches a behavior from the component. | yii\base\Component |
detachBehaviors() | Detaches all behaviors from the component. | yii\base\Component |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\base\Component |
equals() | Returns a value indicating whether the given active record is the same as the current one. | yii\db\BaseActiveRecord |
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\elasticsearch\ActiveQueryInterface instance for query purpose. | yii\elasticsearch\ActiveRecord |
findAll() | Returns a list of active record models that match the specified primary key value(s) or a set of column values. | yii\elasticsearch\ActiveRecord |
findOne() | Returns a single active record model instance by a primary key or an array of column values. | yii\elasticsearch\ActiveRecord |
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 |
get() | Gets a record by its primary key. | yii\elasticsearch\ActiveRecord |
getActiveValidators() | Returns the validators applicable to the current $scenario. | yii\base\Model |
getAttribute() | Returns the named attribute value. | yii\db\BaseActiveRecord |
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 |
getDb() | Returns the database connection used by this AR class. | yii\elasticsearch\ActiveRecord |
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 |
getExplanation() | yii\elasticsearch\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 |
getHighlight() | yii\elasticsearch\ActiveRecord | |
getIsNewRecord() | Returns a value indicating whether the current record is new. | yii\db\BaseActiveRecord |
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\elasticsearch\ActiveRecord |
getPrimaryKey() | Returns the primary key value(s). | yii\elasticsearch\ActiveRecord |
getRelatedRecords() | Returns all populated related records. | yii\db\BaseActiveRecord |
getRelation() | Returns the relation object with the specified name. | yii\db\BaseActiveRecord |
getScenario() | Returns the scenario that this model is used in. | yii\base\Model |
getScore() | yii\elasticsearch\ActiveRecord | |
getValidators() | Returns all the validators declared in rules(). | yii\base\Model |
hasAttribute() | Returns a value indicating whether the model has an attribute with the specified name. | yii\db\BaseActiveRecord |
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 |
index() | yii\elasticsearch\ActiveRecord | |
init() | Initializes the object. | yii\db\BaseActiveRecord |
insert() | Inserts a document into the associated index using the attribute values of this record. | yii\elasticsearch\ActiveRecord |
instantiate() | Creates an active record instance. | yii\elasticsearch\ActiveRecord |
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\BaseActiveRecord |
isRelationPopulated() | Check whether the named relation has been populated with records. | yii\db\BaseActiveRecord |
link() | Establishes the relationship between two models. | yii\db\BaseActiveRecord |
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 |
mget() | Gets a list of records by its primary keys. | yii\elasticsearch\ActiveRecord |
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() | This method has no effect in Elasticsearch ActiveRecord. | yii\elasticsearch\ActiveRecord |
populateRecord() | Populates an active record object using a row of data from the database/storage. | yii\elasticsearch\ActiveRecord |
populateRelation() | Populates the named relation with the related records. | yii\db\BaseActiveRecord |
primaryKey() | This method defines the attribute that uniquely identifies a record. | yii\elasticsearch\ActiveRecord |
refresh() | Repopulates this active record with the latest data. | yii\db\BaseActiveRecord |
rules() | Returns the validation rules for attributes. | yii\base\Model |
safeAttributes() | Returns the attribute names that are safe to be massively assigned in the current scenario. | yii\base\Model |
save() | Saves the current record. | yii\db\BaseActiveRecord |
scenarios() | Returns a list of scenarios and the corresponding active attributes. | yii\base\Model |
setAttribute() | Sets the named attribute value. | yii\db\BaseActiveRecord |
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 |
setPrimaryKey() | Sets the primary key | yii\elasticsearch\ActiveRecord |
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 |
type() | yii\elasticsearch\ActiveRecord | |
unlink() | Destroys the relationship between two models. | yii\db\BaseActiveRecord |
unlinkAll() | Destroys the relationship in current model. | yii\elasticsearch\ActiveRecord |
update() | Saves the changes to this active record into the associated database table. | yii\elasticsearch\ActiveRecord |
updateAll() | Updates all records whos primary keys are given. | yii\elasticsearch\ActiveRecord |
updateAllCounters() | Updates all matching records using the provided counter changes and conditions. | yii\elasticsearch\ActiveRecord |
updateAttributes() | Updates the specified attributes. | yii\db\BaseActiveRecord |
updateCounters() | Updates one or several counter columns for the current AR object. | yii\db\BaseActiveRecord |
validate() | Performs the data validation. | yii\base\Model |
validateMultiple() | Validates multiple models. | yii\base\Model |
Method | Description | Defined By |
---|---|---|
createRelationQuery() | Creates a query instance for has-one or has-many relation. | yii\db\BaseActiveRecord |
findByCondition() | Finds ActiveRecord instance(s) by the given condition. | yii\db\BaseActiveRecord |
primaryKeysByCondition() | Performs a quick and highly efficient scroll/scan query to get the list of primary keys that satisfy the given condition. If condition is a list of primary keys (e.g.: ['_id' => ['1', '2', '3']] ), the query is not performed for performance considerations. | yii\elasticsearch\ActiveRecord |
resolveFields() | Determines which fields can be returned by toArray(). | yii\base\ArrayableTrait |
updateInternal() | yii\elasticsearch\ActiveRecord |
Event | Type | Description | Defined 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 |
Constant | Value | Description | Defined By |
---|---|---|---|
SCENARIO_DEFAULT | 'default' | The name of the default scenario. | yii\base\Model |
An explanation for each hit on how its score was computed.
public array|null getExplanation ( )
A list of arrays with highlighted excerpts indexed by field names.
public array|null getHighlight ( )
The old primary key value. An array (column name => column value) is returned if the primary key is composite or $asArray
is true
. A string is returned otherwise (null will be returned if the key value is null).
public mixed getOldPrimaryKey ( $asArray = false )
The primary key value. An array (column name => column value) is returned if the primary key is composite or $asArray
is true
. A string is returned otherwise (null will be returned if the key value is null).
public mixed getPrimaryKey ( $asArray = false )
public void setPrimaryKey ( $value )
Returns the score of this record when it was retrieved via a find() query.
public float getScore ( )
A list of attributes that should be treated as array valued when retrieved through yii\elasticsearch\ActiveQuery::fields().
If not listed by this method, attributes retrieved through yii\elasticsearch\ActiveQuery::fields() will converted to a scalar value when the result array contains only one value.
public string[] arrayAttributes ( ) | ||
---|---|---|
return | string[] |
List of attribute names. Must be a subset of attributes(). |
Returns the list of all attribute names of the model.
This method must be overridden by child classes to define available attributes.
Attributes are names of fields of the corresponding elasticsearch document. The primaryKey for elasticsearch documents is the _id
field by default which is not part of the attributes. You may define path mapping for the _id
field so that it is part of the _source
fields and thus becomes part of the attributes.
public string[] attributes ( ) | ||
---|---|---|
return | string[] |
List of attribute names. |
throws | yii\base\InvalidConfigException |
if not overridden in a child class. |
Deletes the table row corresponding to this active record.
This method performs the following steps in order:
false
, it will skip the rest of the steps;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 ( $options = [] ) | ||
---|---|---|
$options | array |
Options given in this parameter are passed to elasticsearch as request URI parameters. These are among others:
Please refer to the elasticsearch documentation for more details on these options. The following parameters are Yii specific:
|
return | integer|boolean |
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 optimistic locking is enabled and the data being deleted is outdated. |
throws | yii\elasticsearch\Exception |
in case delete failed. |
Deletes rows in the table using the provided conditions.
WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
For example, to delete all customers whose status is 3:
Customer::deleteAll(['status' => 3]);
See also [[yii\elasticsearch\ActiveRecord::primaryKeysByCondition()]].
public static integer deleteAll ( $condition = [] ) | ||
---|---|---|
$condition | array |
The conditions that will be passed to the |
return | integer |
The number of rows deleted |
throws | yii\elasticsearch\Exception |
on error. |
Creates an \yii\elasticsearch\ActiveQueryInterface instance for query purpose.
The returned \yii\elasticsearch\ActiveQueryInterface instance can be further customized by calling methods defined in \yii\elasticsearch\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\db\BaseActiveRecord::hasOne() and yii\db\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\elasticsearch\ActiveQuery find ( ) | ||
---|---|---|
return | yii\elasticsearch\ActiveQuery |
The newly created yii\elasticsearch\ActiveQuery instance. |
Returns a list of active record models that match the specified primary key value(s) or a set of column values.
The method accepts:
WHERE
condition.['id' => 1, 2]
is treated as a non-associative array.This method will automatically call the all()
method and return an array of \yii\elasticsearch\ActiveRecordInterface instances.
Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work. If you need to specify more complex conditions, use find() in combination with where() instead.
See the following code for usage examples:
// find the customers whose primary key value is 10 $customers = Customer::findAll(10); // the above code is equivalent to: $customers = Customer::find()->where(['id' => 10])->all(); // find the customers whose primary key value is 10, 11 or 12. $customers = Customer::findAll([10, 11, 12]); // the above code is equivalent to: $customers = Customer::find()->where(['id' => [10, 11, 12]])->all(); // find customers whose age is 30 and whose status is 1 $customers = Customer::findAll(['age' => 30, 'status' => 1]); // the above code is equivalent to: $customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();
public static static[] findAll ( $condition ) | ||
---|---|---|
$condition | mixed |
Primary key value or a set of column values |
return | static[] |
An array of ActiveRecord instances, or an empty array if nothing matches. |
Returns a single active record model instance by a primary key or an array of column values.
The method accepts:
null
if not found).null
if not found).null
if not found). Note that ['id' => 1, 2]
is treated as a non-associative array.That this method will automatically call the one()
method and return an \yii\elasticsearch\ActiveRecordInterface instance.
Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work. If you need to specify more complex conditions, use find() in combination with where() instead.
See the following code for usage examples:
// find a single customer whose primary key value is 10 $customer = Customer::findOne(10); // the above code is equivalent to: $customer = Customer::find()->where(['id' => 10])->one(); // find the customers whose primary key value is 10, 11 or 12. $customers = Customer::findOne([10, 11, 12]); // the above code is equivalent to: $customers = Customer::find()->where(['id' => [10, 11, 12]])->one(); // find the first customer whose age is 30 and whose status is 1 $customer = Customer::findOne(['age' => 30, 'status' => 1]); // the above code is equivalent to: $customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
public static static findOne ( $condition ) | ||
---|---|---|
$condition | mixed |
Primary key value or a set of column values |
return | static |
ActiveRecord instance matching the condition, or |
Gets a record by its primary key.
public static static|null get ( $primaryKey, $options = [] ) | ||
---|---|---|
$primaryKey | mixed |
The primaryKey value |
$options | array |
Options given in this parameter are passed to elasticsearch as request URI parameters. Please refer to the elasticsearch documentation for more details on these options. |
return | static|null |
The record instance or null if it was not found. |
Returns the database connection used by this AR class.
By default, the "elasticsearch" application component is used as the database connection. You may override this method if you want to use a different database connection.
public static yii\elasticsearch\Connection getDb ( ) | ||
---|---|---|
return | yii\elasticsearch\Connection |
The database connection used by this AR class. |
public array|null getExplanation ( ) | ||
---|---|---|
return | array|null |
An explanation for each hit on how its score was computed. |
public array|null getHighlight ( ) | ||
---|---|---|
return | array|null |
A list of arrays with highlighted excerpts indexed by field names. |
Returns the old primary key value(s).
This refers to the primary key value that is populated into the record after executing a find method (e.g. find(), findOne()). The value remains unchanged even if the primary key attribute is manually assigned with a different value.
public mixed getOldPrimaryKey ( $asArray = false ) | ||
---|---|---|
$asArray | boolean |
Whether to return the primary key value as an array. If |
return | mixed |
The old primary key value. An array (column name => column value) is returned if the primary key is composite or |
throws | yii\db\Exception |
if the AR model does not have a primary key |
Returns the primary key value(s).
public mixed getPrimaryKey ( $asArray = false ) | ||
---|---|---|
$asArray | boolean |
Whether to return the primary key value as an array. If |
return | mixed |
The primary key value. An array (column name => column value) is returned if the primary key is composite or |
public float getScore ( ) | ||
---|---|---|
return | float |
Returns the score of this record when it was retrieved via a find() query. |
public static string index ( ) | ||
---|---|---|
return | string |
The name of the index this record is stored in. |
Inserts a document into the associated index using the attribute values of this record.
This method performs the following steps in order:
$runValidation
is true. If validation fails, it will skip the rest of the steps;$runValidation
is true.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 changed attribute values will be inserted into database.
If the primary key is not set (null) during insertion, it will be populated with a randomly generated 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, $options = ['op_type' => 'create'] ) | ||
---|---|---|
$runValidation | boolean |
Whether to perform validation before saving the record. If the validation fails, the record will not be inserted into the database. |
$attributes | array |
List of attributes that need to be saved. Defaults to null, meaning all attributes will be saved. |
$options | array |
Options given in this parameter are passed to elasticsearch as request URI parameters. These are among others:
Please refer to the elasticsearch documentation for more details on these options. By default the |
return | boolean |
Whether the attributes are valid and the record is inserted successfully. |
Creates an active record instance.
This method is called together with populateRecord() by yii\elasticsearch\ActiveQuery. It is not meant to be used for creating new records directly.
You may override this method if the instance being created depends on the row data to be populated into the record. For example, by creating a record based on the value of a column, you may implement the so-called single-table inheritance mapping.
public static static instantiate ( $row ) | ||
---|---|---|
$row | array |
Row data to be populated into the record. This array consists of the following keys:
|
return | static |
The newly created active record |
Gets a list of records by its primary keys.
public static array mget ( array $primaryKeys, $options = [] ) | ||
---|---|---|
$primaryKeys | array |
An array of primaryKey values |
$options | array |
Options given in this parameter are passed to elasticsearch as request URI parameters. Please refer to the elasticsearch documentation for more details on these options. |
return | array |
The record instances, or empty array if nothing was found |
This method has no effect in Elasticsearch ActiveRecord.
Elasticsearch ActiveRecord uses native Optimistic locking. See update() for more details.
public void optimisticLock ( ) |
---|
Populates an active record object using a row of data from the database/storage.
This is an internal method meant to be called to create active record objects after fetching data from the database. It is mainly used by yii\elasticsearch\ActiveQuery to populate the query results into active records.
When calling this method manually you should call afterFind() on the created record to trigger the afterFind Event.
public static void populateRecord ( $record, $row ) | ||
---|---|---|
$record | yii\elasticsearch\ActiveRecord |
The record to be populated. In most cases this will be an instance created by instantiate() beforehand. |
$row | array |
Attribute values (name => value) |
This method defines the attribute that uniquely identifies a record.
The primaryKey for elasticsearch documents is the _id
field by default. This field is not part of the ActiveRecord attributes so you should never add _id
to the list of attributes.
You may override this method to define the primary key name when you have defined path mapping for the _id
field so that it is part of the _source
and thus part of the attributes.
Note that elasticsearch only supports one attribute to be the primary key. However to match the signature of the ActiveRecordInterface this methods returns an array instead of a single string.
public static string[] primaryKey ( ) | ||
---|---|---|
return | string[] |
Array of primary key attributes. Only the first element of the array will be used. |
Performs a quick and highly efficient scroll/scan query to get the list of primary keys that satisfy the given condition. If condition is a list of primary keys (e.g.: ['_id' => ['1', '2', '3']]
), the query is not performed for performance considerations.
See also:
protected static array primaryKeysByCondition ( $condition ) | ||
---|---|---|
$condition | array |
Please refer to yii\elasticsearch\ActiveQuery::where() on how to specify this parameter |
return | array |
Primary keys that correspond to given conditions |
Sets the primary key
public void setPrimaryKey ( $value ) | ||
---|---|---|
$value | mixed | |
throws | yii\base\InvalidCallException |
when record is not new |
public static string type ( ) | ||
---|---|---|
return | string |
The name of the type of this record. |
Destroys the relationship in current model.
This method is not supported by elasticsearch.
public void unlinkAll ( $name, $delete = false ) | ||
---|---|---|
$name | ||
$delete |
Saves the changes to this active record into the associated database table.
This method performs the following steps in order:
$runValidation
is true
. If beforeValidate() returns false
, the rest of the steps will be skipped;$runValidation
is true
. If validation failed, the rest of the steps will be skipped;false
, the rest of the steps will be skipped;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 changed attribute values 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|boolean update ( $runValidation = true, $attributeNames = null, $options = [] ) | ||
---|---|---|
$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 attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved. |
$options | array |
Options given in this parameter are passed to elasticsearch as request URI parameters. These are among others:
Please refer to the elasticsearch documentation for more details on these options. The following parameters are Yii specific:
|
return | integer|boolean |
The number of rows affected, or false if validation fails or beforeSave() stops the updating process. |
throws | yii\db\StaleObjectException |
if optimistic locking is enabled and the data being updated is outdated. |
throws | yii\base\InvalidParamException |
if no \yii\elasticsearch\version is available and optimistic locking is enabled. |
throws | yii\elasticsearch\Exception |
in case update failed. |
Updates all records whos primary keys are given.
For example, to change the status to be 1 for all customers whose status is 2:
Customer::updateAll(['status' => 1], ['status' => 2]);
See also [[yii\elasticsearch\ActiveRecord::primaryKeysByCondition()]].
public static integer updateAll ( $attributes, $condition = [] ) | ||
---|---|---|
$attributes | array |
Attribute values (name-value pairs) to be saved into the table |
$condition | array |
The conditions that will be passed to the |
return | integer |
The number of rows updated |
throws | yii\elasticsearch\Exception |
on error. |
Updates all matching records using the provided counter changes and conditions.
For example, to add 1 to age of all customers whose status is 2,
Customer::updateAllCounters(['age' => 1], ['status' => 2]);
See also [[yii\elasticsearch\ActiveRecord::primaryKeysByCondition()]].
public static integer updateAllCounters ( $counters, $condition = [] ) | ||
---|---|---|
$counters | array |
The counters to be updated (attribute name => increment value). Use negative values if you want to decrement the counters. |
$condition | array |
The conditions that will be passed to the |
return | integer |
The number of rows updated |
throws | yii\elasticsearch\Exception |
on error. |
See also update().
protected integer|false updateInternal ( $attributes = null, $options = [] ) | ||
---|---|---|
$attributes | array |
Attributes to update |
$options | array |
Options given in this parameter are passed to elasticsearch as request URI parameters. See update() for details. |
return | integer|false |
The number of rows affected, or false if beforeSave() stops the updating process. |
throws | yii\db\StaleObjectException |
if optimistic locking is enabled and the data being updated is outdated. |
throws | yii\base\InvalidParamException |
if no \yii\elasticsearch\version is available and optimistic locking is enabled. |
throws | yii\elasticsearch\Exception |
in case update failed. |
© 2008–2017 by Yii Software LLC
Licensed under the three clause BSD license.
http://www.yiiframework.com/doc-2.0/yii-elasticsearch-activerecord.html