Class yii\elasticsearch\ActiveRecord
Inheritance | yii\elasticsearch\ActiveRecord » yii\db\BaseActiveRecord » yii\base\Model » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | ArrayAccess, IteratorAggregate, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface, yii\db\ActiveRecordInterface |
Uses Traits | yii\base\ArrayableTrait, yii\base\StaticInstanceTrait |
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.
IMPORTANT: The primary key (the _id
attribute) MUST NOT be included in attributes().
The following is an example model called Customer
:
class Customer extends \yii\elasticsearch\ActiveRecord
{
public function attributes()
{
return ['name', 'address', 'registration_date'];
}
}
You may override index() and type() to define the index and type this record represents. Types are being deprecated, and it is recommended to have a single type per index. For more information read about removal of mapping types. For Elasticsearch 7 and later (as configured in yii\elasticsearch\Connection, type() is ignored.
Public Methods
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | yii\base\Component |
__clone() | This method is called after the object is created by cloning an existing one. | yii\base\Component |
__construct() | Constructor. | yii\base\BaseObject |
__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() | {@inheritdoc} | yii\db\BaseActiveRecord |
canSetProperty() | {@inheritdoc} | yii\db\BaseActiveRecord |
className() | Returns the fully qualified name of this class. | yii\base\BaseObject |
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\db\ActiveQueryInterface instance for query purpose. | yii\elasticsearch\ActiveRecord |
findAll() | {@inheritdoc} | yii\elasticsearch\ActiveRecord |
findOne() | {@inheritdoc} | 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 \yii\base\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 |
getErrorSummary() | Returns the errors for all attributes as a one-dimensional array. | yii\base\Model |
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() | Alias to get_id(). Returns the primary key value. | 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 |
get_id() | Returns the _id attribute that holds the primary key (for compatibility with relations) |
yii\elasticsearch\ActiveRecord |
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\Component |
hasOne() | Declares a has-one relation. |
yii\db\BaseActiveRecord |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\base\Component |
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 |
instance() | Returns static class instance, which can be used to obtain meta information. | yii\base\StaticInstanceTrait |
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() | yii\elasticsearch\ActiveRecord | |
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() | Alias to set_id(). Sets the primary key value. | yii\elasticsearch\ActiveRecord |
setScenario() | Sets the scenario for the model. | yii\base\Model |
set_id() | Sets the _id attribute that holds the primary key (for compatibility with relations) |
yii\elasticsearch\ActiveRecord |
toArray() | Converts the model into an array. | yii\base\ArrayableTrait |
trigger() | Triggers an event. | yii\base\Component |
type() | Returns the name of the type of this record. | 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 that match a certain condition. | 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 |
Protected Methods
Method | Description | Defined By |
---|---|---|
createRelationQuery() | Creates a query instance for has-one or has-many relation. |
yii\db\BaseActiveRecord |
extractFieldsFor() | Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id". | yii\base\ArrayableTrait |
extractRootFields() | Extracts the root field names from nested fields. | yii\base\ArrayableTrait |
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 |
refreshInternal() | Repopulates this active record with the latest data from a newly fetched instance. | yii\db\BaseActiveRecord |
resolveFields() | Determines which fields can be returned by toArray(). | yii\base\ArrayableTrait |
updateInternal() | yii\elasticsearch\ActiveRecord | |
validateViaRelationLink() | Validates model so that it does not contain array as its keys while linking. | yii\elasticsearch\ActiveRecord |
Events
Event | Type | Description | Defined By |
---|---|---|---|
EVENT_AFTER_DELETE | \yii\db\Event | An event that is triggered after a record is deleted. | yii\db\BaseActiveRecord |
EVENT_AFTER_FIND | \yii\db\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\db\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\db\Event | An event that is triggered when the record is initialized via init(). | yii\db\BaseActiveRecord |
Constants
Constant | Value | Description | Defined By |
---|---|---|---|
SCENARIO_DEFAULT | 'default' | The name of the default scenario. | yii\base\Model |
Method Details
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.
IMPORTANT: The primary key (the _id
attribute) MUST NOT be included in attributes().
Attributes are names of fields of the corresponding Elasticsearch document.
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:
- call beforeDelete(). If the method returns
false
, it will skip the rest of the steps; - delete the record from the database;
- 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 ( $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\db\ActiveQueryInterface instance for query purpose.
The returned yii\db\ActiveQueryInterface instance can be further customized by calling
methods defined in yii\db\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. |
---|
{@inheritdoc}
public static static[] findAll ( $condition ) | ||
$condition | ||
return | static[] | An array of ActiveRecord instances, or an empty array if nothing matches. |
---|
{@inheritdoc}
public static static|null findOne ( $condition ) | ||
$condition | ||
return | static|null | 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 |
Alias to get_id(). Returns the primary key value.
public mixed getPrimaryKey ( $asArray = false ) | ||
$asArray | boolean |
public float getScore ( ) | ||
return | float | Returns the score of this record when it was retrieved via a find() query. |
---|
Returns the _id
attribute that holds the primary key (for compatibility with relations)
public mixed get_id ( ) |
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:
- call beforeValidate() when
$runValidation
is true. If validation fails, it will skip the rest of the steps; - call afterValidate() when
$runValidation
is true. - call beforeSave(). If the method returns false, it will skip the rest of the steps;
- insert the record into database. If this fails, it will skip the rest of the steps;
- 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 \yii\elasticsearch\dirtyAttributes 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 = [] ) | ||
$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 |
---|
public void link ( $name, $model, $extraColumns = [] ) | ||
$name | ||
$model | ||
$extraColumns |
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 name of the primary key attribute is _id
, and can not be changed.
Elasticsearch does not support composite primary keys in the traditional sense. 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 |
---|
Alias to set_id(). Sets the primary key value.
public void setPrimaryKey ( $value ) | ||
$value | mixed | |
throws | yii\base\InvalidCallException | when record is not new |
---|
Sets the _id
attribute that holds the primary key (for compatibility with relations)
public void set_id ( $value ) | ||
$value | mixed | |
throws | yii\base\InvalidCallException | when record is not new |
---|
Returns the name of the type of this record.
IMPORTANT: For Elasticsearch 7 and later, type() is ignored.
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:
- call beforeValidate() when
$runValidation
istrue
. If beforeValidate() returnsfalse
, the rest of the steps will be skipped; - call afterValidate() when
$runValidation
istrue
. If validation failed, the rest of the steps will be skipped; - call beforeSave(). If beforeSave() returns
false
, the rest of the steps will be skipped; - save the record into database. If this fails, it will skip the rest of the steps;
- 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 \yii\elasticsearch\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|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\elasticsearch\InvalidParamException | if no \yii\elasticsearch\version is available and optimistic locking is enabled. |
throws | yii\elasticsearch\Exception | in case update failed. |
Updates all records that match a certain condition.
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\elasticsearch\InvalidParamException | if no \yii\elasticsearch\version is available and optimistic locking is enabled. |
throws | yii\elasticsearch\Exception | in case update failed. |
Validates model so that it does not contain array as its keys while linking.
protected void validateViaRelationLink ( $model, $relation ) | ||
$model | yii\db\ActiveRecordInterface | The model to be linked with the current one. |
$relation |