PHP Class yii\db\ActiveQuery
An ActiveQuery can be a normal query or be used in a relational context.
ActiveQuery instances are usually created by [[ActiveRecord::find()]] and [[ActiveRecord::findBySql()]].
Relational queries are created by [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]].
Normal Query
------------
ActiveQuery mainly provides the following methods to retrieve the query results:
-
ActiveQuery::one: returns a single record populated with the first row of data.
-
ActiveQuery::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.
- [[column()]]: returns the value of the first column in the query result.
- [[exists()]]: returns a value indicating whether the query result has data or not.
Because ActiveQuery extends from
Query, one can use query methods, such as [[where()]],
[[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.
-
ActiveQuery::joinWith: reuse a relation query definition to add a join to a query.
- [[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:
php
$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()]] or
ActiveQuery::viaTable method.
These methods may only be called in a relational context. Same is true for [[inverseOf()]], which
marks a relation as inverse of another relation and
ActiveQuery::onCondition which adds a condition that
is to be added to relational query join condition.
显示文件
Open project: yiisoft/yii2
Class Usage Examples
Public Properties
Property |
Type |
Description |
|
$joinWith |
|
a list of relations that this query should be joined with |
|
$on |
|
the join condition to be used when this query is used in a relational context.
The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
Otherwise, the condition will be used in the WHERE part of a query.
Please refer to [[Query::where()]] on how to specify this parameter. |
|
$sql |
|
the SQL statement to be executed for retrieving AR records.
This is set by [[ActiveRecord::findBySql()]]. |
|
Public Methods
Protected Methods
Method |
Description |
|
queryScalar ( $selectExpression, $db ) |
|
|
Private Methods
Method Details
__construct()
public method
public __construct ( string $modelClass, array $config = [] ) |
$modelClass |
string |
the model class associated with this query |
$config |
array |
configurations to be applied to the newly created query object |
This method will adjust [[from]] so that an already defined alias will be overwritten.
If none was defined, [[from]] will be populated with the given alias.
Executes query and returns all results as an array.
public all ( Connection $db = null ) : array | ActiveRecord[] |
$db |
Connection |
the DB connection used to create the DB command.
If null, the DB connection returned by [[modelClass]] will be used. |
return |
array | ActiveRecord[] |
the query results. If the query results in nothing, an empty array will be returned. |
andOnCondition()
public method
The new condition and the existing one will be joined using the 'AND' operator.
public andOnCondition ( string | array $condition, array $params = [] ) |
$condition |
string | array |
the new ON condition. Please refer to [[where()]]
on how to specify this parameter. |
$params |
array |
the parameters (name => value) to be bound to the query. |
createCommand()
public method
Creates a DB command that can be used to execute this query.
public createCommand ( Connection | null $db = null ) : Command |
$db |
Connection | null |
the DB connection used to create the DB command.
If `null`, the DB connection returned by [[modelClass]] will be used. |
return |
Command |
the created DB command instance. |
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.
innerJoinWith()
public method
This method allows you to reuse existing relation definitions to perform JOIN queries.
Based on the definition of the specified relation(s), the method will append one or multiple
JOIN statements to the current query.
If the $eagerLoading parameter is true, the method will also perform eager loading for the specified relations,
which is equivalent to calling [[with()]] using the specified relations.
Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement
for the primary table. And when $eagerLoading is true, it will call [[with()]] in addition with the specified relations.
public joinWith ( string | array $with, boolean | array $eagerLoading = true, string | array $joinType = 'LEFT JOIN' ) |
$with |
string | array |
the relations to be joined. This can either be a string, representing a relation name or
an array with the following semantics:
- Each array element represents a single relation.
- You may specify the relation name as the array key and provide an anonymous functions that
can be used to modify the relation queries on-the-fly as the array value.
- If a relation query does not need modification, you may use the relation name as the array value.
The relation name may optionally contain an alias for the relation table (e.g. `books b`).
Sub-relations can also be specified, see [[with()]] for the syntax.
In the following you find some examples:
```php
// find all orders that contain books, and eager loading "books"
Order::find()->joinWith('books', true, 'INNER JOIN')->all();
// find all orders, eager loading "books", and sort the orders and books by the book names.
Order::find()->joinWith([
'books' => function (\yii\db\ActiveQuery $query) {
$query->orderBy('item.name');
}
])->all();
// find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table
Order::find()->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all();
```
The alias syntax is available since version 2.0.7. |
$eagerLoading |
boolean | array |
whether to eager load the relations specified in `$with`.
When this is a boolean, it applies to all relations specified in `$with`. Use an array
to explicitly list which relations in `$with` need to be eagerly loaded. Defaults to `true`. |
$joinType |
string | array |
the join type of the relations specified in `$with`.
When this is a string, it applies to all relations specified in `$with`. Use an array
in the format of `relationName => joinType` to specify different join types for different relations. |
onCondition()
public method
The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
Otherwise, the condition will be used in the WHERE part of a query.
Use this method to specify additional conditions when declaring a relation in the
ActiveRecord class:
php
public function getActiveUsers()
{
return $this->hasMany(User::className(), ['id' => 'user_id'])
->onCondition(['active' => true]);
}
Note that this condition is applied in case of a join as well as when fetching the related records.
Thus only fields of the related table can be used in the condition. Trying to access fields of the primary
record will cause an error in a non-join-query.
public onCondition ( string | array $condition, array $params = [] ) |
$condition |
string | array |
the ON condition. Please refer to [[Query::where()]] on how to specify this parameter. |
$params |
array |
the parameters (name => value) to be bound to the query. |
Executes query and returns a single row of result.
public one ( Connection | null $db = null ) : ActiveRecord | array | null |
$db |
Connection | null |
the DB connection used to create the DB command.
If `null`, the DB connection returned by [[modelClass]] will be used. |
return |
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. |
orOnCondition()
public method
The new condition and the existing one will be joined using the 'OR' operator.
public orOnCondition ( string | array $condition, array $params = [] ) |
$condition |
string | array |
the new ON condition. Please refer to [[where()]]
on how to specify this parameter. |
$params |
array |
the parameters (name => value) to be bound to the query. |
queryScalar()
protected method
Use this method to specify a junction table when declaring a relation in the
ActiveRecord class:
php
public function getItems()
{
return $this->hasMany(Item::className(), ['id' => 'item_id'])
->viaTable('order_item', ['order_id' => 'id']);
}
public viaTable ( string $tableName, array $link, callable $callable = null ) |
$tableName |
string |
the name of the junction table. |
$link |
array |
the link between the junction table and the table associated with [[primaryModel]].
The keys of the array represent the columns in the junction table, and the values represent the columns
in the [[primaryModel]] table. |
$callable |
callable |
a PHP callback for customizing the relation associated with the junction table.
Its signature should be `function($query)`, where `$query` is the query to be customized. |
Property Details
$joinWith public_oe property
a list of relations that this query should be joined with
the join condition to be used when this query is used in a relational context.
The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
Otherwise, the condition will be used in the WHERE part of a query.
Please refer to [[Query::where()]] on how to specify this parameter.
the SQL statement to be executed for retrieving AR records.
This is set by [[ActiveRecord::findBySql()]].