Class yii\redis\ActiveQuery
Inheritance | yii\redis\ActiveQuery » yii\base\Component |
---|---|
Implements | yii\db\ActiveQueryInterface |
Uses Traits | yii\db\ActiveQueryTrait, yii\db\ActiveRelationTrait, yii\db\QueryTrait |
Available since extension's version | 2.0 |
Source Code | https://github.com/yiisoft/yii2-redis/blob/master/src/ActiveQuery.php |
ActiveQuery represents a query associated with an Active Record class.
An ActiveQuery can be a normal query or be used in a relational context.
ActiveQuery instances are usually created by yii\redis\ActiveRecord::find(). Relational queries are created by ActiveRecord::hasOne() and ActiveRecord::hasMany().
Normal Query ¶
ActiveQuery mainly provides the following methods to retrieve the query results:
- one(): returns a single record populated with the first row of data.
- all(): returns all records based on the query results.
- count(): returns the number of records.
- sum(): returns the sum over the specified column.
- average(): returns the average over the specified column.
- min(): returns the min over the specified column.
- max(): returns the max over the specified column.
- scalar(): returns the value of the first column in the first row of the query result.
- exists(): returns a value indicating whether the query result has data or not.
You can use query methods, such as where(), limit() and orderBy() to customize the query options.
ActiveQuery also provides the following additional query options:
- with(): list of relations that this query should be performed with.
- indexBy(): the name of the column by which the query result should be indexed.
- asArray(): whether to return each record as an array.
These options can be configured using methods of the same name. For example:
$customers = Customer::find()->with('orders')->asArray()->all();
Relational query ¶
In relational context ActiveQuery represents a relation between two Active Record classes.
Relational ActiveQuery instances are usually created by calling ActiveRecord::hasOne() and ActiveRecord::hasMany(). An Active Record class declares a relation by defining a getter method which calls one of the above methods and returns the created ActiveQuery object.
A relation is specified by link which represents the association between columns of different tables; and the multiplicity of the relation is indicated by multiple.
If a relation involves a junction table, it may be specified by via(). This methods may only be called in a relational context. Same is true for inverseOf(), which marks a relation as inverse of another relation.
Public Methods
Method | Description | Defined By |
---|---|---|
__construct() | Constructor. | yii\redis\ActiveQuery |
all() | Executes the query and returns all results as an array. | yii\redis\ActiveQuery |
average() | Returns the average of the specified column values. | yii\redis\ActiveQuery |
column() | Executes the query and returns the first column of the result. | yii\redis\ActiveQuery |
count() | Returns the number of records. | yii\redis\ActiveQuery |
exists() | Returns a value indicating whether the query result contains any row of data. | yii\redis\ActiveQuery |
init() | Initializes the object. | yii\redis\ActiveQuery |
max() | Returns the maximum of the specified column values. | yii\redis\ActiveQuery |
min() | Returns the minimum of the specified column values. | yii\redis\ActiveQuery |
one() | Executes the query and returns a single row of result. | yii\redis\ActiveQuery |
scalar() | Returns the query result as a scalar value. | yii\redis\ActiveQuery |
sum() | Returns the number of records. | yii\redis\ActiveQuery |
Protected Methods
Method | Description | Defined By |
---|---|---|
executeScript() | Executes a script created by yii\redis\LuaScriptBuilder | yii\redis\ActiveQuery |
Events
Event | Type | Description | Defined By |
---|---|---|---|
EVENT_INIT | yii\redis\Event | An event that is triggered when the query is initialized via init(). | yii\redis\ActiveQuery |
Method Details
Constructor.
public void __construct ( $modelClass, $config = [] ) | ||
$modelClass | string |
The model class associated with this query |
$config | array |
Configurations to be applied to the newly created query object |
public function __construct($modelClass, $config = [])
{
$this->modelClass = $modelClass;
parent::__construct($config);
}
Executes the query and returns all results as an array.
public array|yii\redis\ActiveRecord[] all ( $db = null ) | ||
$db | yii\redis\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | array|yii\redis\ActiveRecord[] |
The query results. If the query results in nothing, an empty array will be returned. |
---|
public function all($db = null)
{
if ($this->emulateExecution) {
return [];
}
// TODO add support for orderBy
$data = $this->executeScript($db, 'All');
if (empty($data)) {
return [];
}
$rows = [];
foreach ($data as $dataRow) {
$row = [];
$c = count($dataRow);
for ($i = 0; $i < $c;) {
$row[$dataRow[$i++]] = $dataRow[$i++];
}
$rows[] = $row;
}
if (empty($rows)) {
return [];
}
$models = $this->createModels($rows);
if (!empty($this->with)) {
$this->findWith($this->with, $models);
}
if ($this->indexBy !== null) {
$indexedModels = [];
if (is_string($this->indexBy)) {
foreach ($models as $model) {
$key = $model[$this->indexBy];
$indexedModels[$key] = $model;
}
} else {
foreach ($models as $model) {
$key = call_user_func($this->indexBy, $model);
$indexedModels[$key] = $model;
}
}
$models = $indexedModels;
}
if (!$this->asArray) {
foreach ($models as $model) {
$model->afterFind();
}
}
return $models;
}
Returns the average of the specified column values.
public integer average ( $column, $db = null ) | ||
$column | string |
The column name or expression. Make sure you properly quote column names in the expression. |
$db | yii\redis\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | integer |
The average of the specified column values. |
---|
public function average($column, $db = null)
{
if ($this->emulateExecution) {
return 0;
}
return $this->executeScript($db, 'Average', $column);
}
Executes the query and returns the first column of the result.
public array column ( $column, $db = null ) | ||
$column | string |
Name of the column to select |
$db | yii\redis\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | array |
The first column of the query result. An empty array is returned if the query results in nothing. |
---|
public function column($column, $db = null)
{
if ($this->emulateExecution) {
return [];
}
// TODO add support for orderBy
return $this->executeScript($db, 'Column', $column);
}
Returns the number of records.
public integer count ( $q = '*', $db = null ) | ||
$q | string |
The COUNT expression. This parameter is ignored by this implementation. |
$db | yii\redis\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | integer |
Number of records |
---|
public function count($q = '*', $db = null)
{
if ($this->emulateExecution) {
return 0;
}
if ($this->where === null) {
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
if ($db === null) {
$db = $modelClass::getDb();
}
return $db->executeCommand('LLEN', [$modelClass::keyPrefix()]);
}
return $this->executeScript($db, 'Count');
}
Executes a script created by yii\redis\LuaScriptBuilder
protected array|boolean|null|string executeScript ( $db, $type, $columnName = null ) | ||
$db | yii\redis\Connection|null |
The database connection used to execute the query.
If this parameter is not given, the |
$type | string |
The type of the script to generate |
$columnName | string | |
throws | \yii\base\NotSupportedException |
---|
protected function executeScript($db, $type, $columnName = null)
{
if ($this->primaryModel !== null) {
// lazy loading
if ($this->via instanceof self) {
// via junction table
$viaModels = $this->via->findJunctionRows([$this->primaryModel]);
$this->filterByModels($viaModels);
} elseif (is_array($this->via)) {
// via relation
/* @var $viaQuery ActiveQuery */
list($viaName, $viaQuery) = $this->via;
if ($viaQuery->multiple) {
$viaModels = $viaQuery->all();
$this->primaryModel->populateRelation($viaName, $viaModels);
} else {
$model = $viaQuery->one();
$this->primaryModel->populateRelation($viaName, $model);
$viaModels = $model === null ? [] : [$model];
}
$this->filterByModels($viaModels);
} else {
$this->filterByModels([$this->primaryModel]);
}
}
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
if ($db === null) {
$db = $modelClass::getDb();
}
// find by primary key if possible. This is much faster than scanning all records
if (
is_array($this->where)
&& (
(!isset($this->where[0]) && $modelClass::isPrimaryKey(array_keys($this->where)))
|| (isset($this->where[0]) && $this->where[0] === 'in' && $modelClass::isPrimaryKey((array) $this->where[1]))
)
) {
return $this->findByPk($db, $type, $columnName);
}
$method = 'build' . $type;
$script = $db->getLuaScriptBuilder()->$method($this, $columnName);
return $db->executeCommand('EVAL', [$script, 0]);
}
Returns a value indicating whether the query result contains any row of data.
public boolean exists ( $db = null ) | ||
$db | yii\redis\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | boolean |
Whether the query result contains any row of data. |
---|
public function exists($db = null)
{
if ($this->emulateExecution) {
return false;
}
return $this->one($db) !== null;
}
Initializes the object.
This method is called at the end of the constructor. The default implementation will trigger an EVENT_INIT event. If you override this method, make sure you call the parent implementation at the end to ensure triggering of the event.
public void init ( ) |
public function init()
{
parent::init();
$this->trigger(self::EVENT_INIT);
}
Returns the maximum of the specified column values.
public integer max ( $column, $db = null ) | ||
$column | string |
The column name or expression. Make sure you properly quote column names in the expression. |
$db | yii\redis\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | integer |
The maximum of the specified column values. |
---|
public function max($column, $db = null)
{
if ($this->emulateExecution) {
return null;
}
return $this->executeScript($db, 'Max', $column);
}
Returns the minimum of the specified column values.
public integer min ( $column, $db = null ) | ||
$column | string |
The column name or expression. Make sure you properly quote column names in the expression. |
$db | yii\redis\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | integer |
The minimum of the specified column values. |
---|
public function min($column, $db = null)
{
if ($this->emulateExecution) {
return null;
}
return $this->executeScript($db, 'Min', $column);
}
Executes the query and returns a single row of result.
public yii\redis\ActiveRecord|array|null one ( $db = null ) | ||
$db | yii\redis\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | yii\redis\ActiveRecord|array|null |
A single row of query result. Depending on the setting of asArray, the query result may be either an array or an ActiveRecord object. Null will be returned if the query results in nothing. |
---|
public function one($db = null)
{
if ($this->emulateExecution) {
return null;
}
// TODO add support for orderBy
$data = $this->executeScript($db, 'One');
if (empty($data)) {
return null;
}
$row = [];
$c = count($data);
for ($i = 0; $i < $c;) {
$row[$data[$i++]] = $data[$i++];
}
if ($this->asArray) {
$model = $row;
} else {
/* @var $class ActiveRecord */
$class = $this->modelClass;
$model = $class::instantiate($row);
$class = get_class($model);
$class::populateRecord($model, $row);
}
if (!empty($this->with)) {
$models = [$model];
$this->findWith($this->with, $models);
$model = $models[0];
}
if (!$this->asArray) {
$model->afterFind();
}
return $model;
}
Returns the query result as a scalar value.
The value returned will be the specified attribute in the first record of the query results.
public string scalar ( $attribute, $db = null ) | ||
$attribute | string |
Name of the attribute to select |
$db | yii\redis\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | string |
The value of the specified attribute in the first record of the query result. Null is returned if the query result is empty. |
---|
public function scalar($attribute, $db = null)
{
if ($this->emulateExecution) {
return null;
}
$record = $this->one($db);
if ($record !== null) {
return $record->hasAttribute($attribute) ? $record->$attribute : null;
}
return null;
}
Returns the number of records.
public integer sum ( $column, $db = null ) | ||
$column | string |
The column to sum up |
$db | yii\redis\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | integer |
Number of records |
---|
public function sum($column, $db = null)
{
if ($this->emulateExecution) {
return 0;
}
return $this->executeScript($db, 'Sum', $column);
}
Event Details
An event that is triggered when the query is initialized via init().