ActiveQuery
extends Query
in package
implements
ActiveQueryInterface
uses
ActiveQueryTrait, ActiveRelationTrait
ActiveQuery represents a DB 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 [[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:
- [[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.
- [[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.
- [[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:
$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 [[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 [[onCondition()]] which adds a condition that is to be added to relational query join condition.
Tags
Table of Contents
Interfaces
- ActiveQueryInterface
- ActiveQueryInterface defines the common interface to be implemented by active record query classes.
Constants
- EVENT_INIT = 'init'
Properties
- $asArray : bool
- $behaviors : array<string|int, Behavior>
- $distinct : bool
- $emulateExecution : bool
- $from : array<string|int, mixed>|null
- $groupBy : array<string|int, mixed>|null
- $having : string|array<string|int, mixed>|ExpressionInterface|null
- $indexBy : string|callable|null
- $inverseOf : string
- $join : array<string|int, mixed>|null
- $joinWith : array<string|int, mixed>|null
- $limit : int|ExpressionInterface|null
- $link : array<string|int, mixed>
- $modelClass : string
- $multiple : bool
- $offset : int|ExpressionInterface|null
- $on : string|array<string|int, mixed>|null
- $orderBy : array<string|int, mixed>|null
- $params : array<string|int, mixed>|null
- $primaryModel : ActiveRecord
- $queryCacheDependency : Dependency|null
- $queryCacheDuration : int|bool|null
- $select : array<string|int, mixed>|null
- $selectOption : string|null
- $sql : string|null
- $tablesUsedInFrom : array<string|int, string>
- $union : array<string|int, mixed>|null
- $via : array<string|int, mixed>|object
- $where : string|array<string|int, mixed>|ExpressionInterface|null
- $with : array<string|int, mixed>
- $withQueries : array<string|int, mixed>|null
- $_behaviors : array<string|int, Behavior>|null
- $_events : array<string|int, mixed>
- $_eventWildcards : array<string|int, mixed>
- $viaMap : mixed
Methods
- __call() : mixed
- Calls the named method which is not a class method.
- __clone() : mixed
- Clones internal objects.
- __construct() : mixed
- Constructor.
- __get() : mixed
- Returns the value of a component property.
- __isset() : bool
- Checks if a property is set, i.e. defined and not null.
- __set() : mixed
- Sets the value of a component property.
- __toString() : string
- Returns the SQL representation of Query
- __unset() : mixed
- Sets a component property to be null.
- addGroupBy() : $this
- Adds additional group-by columns to the existing ones.
- addOrderBy() : $this
- Adds additional ORDER BY columns to the query.
- addParams() : $this
- Adds additional parameters to be bound to the query.
- addSelect() : $this
- Add more columns to the SELECT part of the query.
- alias() : $this
- Define an alias for the table defined in [[modelClass]].
- all() : array<string|int, mixed>|array<string|int, ActiveRecord>
- Executes query and returns all results as an array.
- andFilterCompare() : $this
- Adds a filtering condition for a specific column and allow the user to choose a filter operator.
- andFilterHaving() : $this
- Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
- andFilterWhere() : $this
- Adds an additional WHERE condition to the existing one but ignores [[isEmpty()|empty operands]].
- andHaving() : $this
- Adds an additional HAVING condition to the existing one.
- andOnCondition() : $this
- Adds an additional ON condition to the existing one.
- andWhere() : $this
- Adds an additional WHERE condition to the existing one.
- asArray() : $this
- Sets the [[asArray]] property.
- attachBehavior() : Behavior
- Attaches a behavior to this component.
- attachBehaviors() : mixed
- Attaches a list of behaviors to the component.
- average() : mixed
- Returns the average of the specified column values.
- batch() : BatchQueryResult
- Starts a batch query.
- behaviors() : array<string|int, mixed>
- Returns a list of behaviors that this component should behave as.
- cache() : $this
- Enables query cache for this Query.
- canGetProperty() : bool
- Returns a value indicating whether a property can be read.
- canSetProperty() : bool
- Returns a value indicating whether a property can be set.
- className() : string
- Returns the fully qualified name of this class.
- column() : array<string|int, mixed>
- Executes the query and returns the first column of the result.
- count() : int|string|null
- Returns the number of records.
- create() : Query
- Creates a new Query object and copies its property values from an existing one.
- createCommand() : Command
- Creates a DB command that can be used to execute this query.
- detachBehavior() : Behavior|null
- Detaches a behavior from the component.
- detachBehaviors() : mixed
- Detaches all behaviors from the component.
- distinct() : $this
- Sets the value indicating whether to SELECT DISTINCT or not.
- each() : BatchQueryResult
- Starts a batch query and retrieves data row by row.
- emulateExecution() : $this
- Sets whether to emulate query execution, preventing any interaction with data storage.
- ensureBehaviors() : mixed
- Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
- exists() : bool
- Returns a value indicating whether the query result contains any row of data.
- filterHaving() : $this
- Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
- filterWhere() : $this
- Sets the WHERE part of the query but ignores [[isEmpty()|empty operands]].
- findFor() : mixed
- Finds the related records for the specified primary record.
- findWith() : mixed
- Finds records corresponding to one or multiple relations and populates them into the primary models.
- from() : $this
- Sets the FROM part of the query.
- getBehavior() : Behavior|null
- Returns the named behavior object.
- getBehaviors() : array<string|int, Behavior>
- Returns all behaviors attached to this component.
- getTablesUsedInFrom() : array<string|int, string>
- Returns table names used in [[from]] indexed by aliases.
- groupBy() : $this
- Sets the GROUP BY part of the query.
- hasEventHandlers() : bool
- Returns a value indicating whether there is any handler attached to the named event.
- hasMethod() : bool
- Returns a value indicating whether a method is defined.
- hasProperty() : bool
- Returns a value indicating whether a property is defined for this component.
- having() : $this
- Sets the HAVING part of the query.
- indexBy() : $this
- Sets the [[indexBy]] property.
- init() : mixed
- Initializes the object.
- innerJoin() : $this
- Appends an INNER JOIN part to the query.
- innerJoinWith() : $this
- Inner joins with the specified relations.
- inverseOf() : $this
- Sets the name of the relation that is the inverse of this relation.
- join() : $this
- Appends a JOIN part to the query.
- joinWith() : $this
- Joins with the specified relations.
- leftJoin() : $this
- Appends a LEFT OUTER JOIN part to the query.
- limit() : $this
- Sets the LIMIT part of the query.
- max() : mixed
- Returns the maximum of the specified column values.
- min() : mixed
- Returns the minimum of the specified column values.
- noCache() : $this
- Disables query cache for this Query.
- off() : bool
- Detaches an existing event handler from this component.
- offset() : $this
- Sets the OFFSET part of the query.
- on() : mixed
- Attaches an event handler to an event.
- onCondition() : $this
- Sets the ON condition for a relational query.
- one() : ActiveRecord|array<string|int, mixed>|null
- Executes query and returns a single row of result.
- orderBy() : $this
- Sets the ORDER BY part of the query.
- orFilterHaving() : $this
- Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
- orFilterWhere() : $this
- Adds an additional WHERE condition to the existing one but ignores [[isEmpty()|empty operands]].
- orHaving() : $this
- Adds an additional HAVING condition to the existing one.
- orOnCondition() : $this
- Adds an additional ON condition to the existing one.
- orWhere() : $this
- Adds an additional WHERE condition to the existing one.
- params() : $this
- Sets the parameters to be bound to the query.
- populate() : array<string|int, mixed>
- Converts the raw query results into the format as specified by this query.
- populateRelation() : array<string|int, mixed>
- Finds the related records and populates them into the primary models.
- prepare() : $this
- Prepares for building SQL.
- rightJoin() : $this
- Appends a RIGHT OUTER JOIN part to the query.
- scalar() : string|int|null|false
- Returns the query result as a scalar value.
- select() : $this
- Sets the SELECT part of the query.
- sum() : mixed
- Returns the sum of the specified column values.
- trigger() : mixed
- Triggers an event.
- union() : $this
- Appends a SQL statement using UNION operator.
- via() : $this
- Specifies the relation associated with the junction table.
- viaTable() : $this
- Specifies the junction table for a relational query.
- where() : $this
- Sets the WHERE part of the query.
- with() : $this
- Specifies the relations with which this query should be performed.
- withQuery() : $this
- Prepends a SQL statement using WITH syntax.
- cleanUpTableNames() : array<string|int, string>
- Clean up table names and aliases Both aliases and names are enclosed into {{ and }}.
- createModels() : array<string|int, mixed>|array<string|int, ActiveRecord>
- Converts found rows into model instances.
- filterCondition() : array<string|int, mixed>
- Removes [[isEmpty()|empty operands]] from the given query condition.
- getPrimaryTableName() : string
- getTableNameAndAlias() : array<string|int, mixed>
- Returns the table name and the table alias for [[modelClass]].
- getUnaliasedColumnsFromSelect() : array<string|int, mixed>
- getUniqueColumns() : mixed
- Returns unique column names excluding duplicates.
- isEmpty() : bool
- Returns a value indicating whether the give value is "empty".
- normalizeOrderBy() : array<string|int, mixed>
- Normalizes format of ORDER BY data.
- normalizeSelect() : array<string|int, mixed>
- Normalizes the SELECT columns passed to [[select()]] or [[addSelect()]].
- queryScalar() : bool|string|null
- Queries a scalar value by setting [[select]] first.
- setCommandCache() : Command
- Sets $command cache, if this query has enabled caching.
- addInverseRelations() : mixed
- If applicable, populate the query's primary model into the related records' inverse relationship.
- attachBehaviorInternal() : Behavior
- Attaches a behavior to this component.
- buildBuckets() : array<string|int, mixed>
- buildJoinWith() : mixed
- ensureNameQuoted() : string
- Ensures name is wrapped with {{ and }}
- filterByModels() : mixed
- findJunctionRows() : array<string|int, mixed>
- getJoinType() : string
- Returns the join type based on the given join type parameter and the relation name.
- getModelKey() : string|false
- indexBuckets() : array<string|int, mixed>
- Indexes buckets by column name.
- joinWithRelation() : mixed
- Joins a parent query with a child query.
- joinWithRelations() : mixed
- Modifies the current query by adding join fragments based on the given relations.
- mapVia() : array<string|int, mixed>
- normalizeModelKey() : string
- normalizeRelations() : array<string|int, ActiveQueryInterface>
- populateInverseRelation() : mixed
- prefixKeyColumns() : array<string|int, mixed>
- removeDuplicatedModels() : array<string|int, mixed>
- Removes duplicated models by checking their primary key values.
Constants
EVENT_INIT
public
mixed
EVENT_INIT
= 'init'
Tags
Properties
$asArray
public
bool
$asArray
whether to return each record as an array. If false (default), an object of [[modelClass]] will be created to represent each record.
$behaviors read-only
public
array<string|int, Behavior>
$behaviors
List of behaviors attached to this component.
$distinct
public
bool
$distinct
= false
whether to select distinct rows of data only. If this is set true, the SELECT clause would be changed to SELECT DISTINCT.
$emulateExecution
public
bool
$emulateExecution
= false
whether to emulate the actual query execution, returning empty or false results.
Tags
$from
public
array<string|int, mixed>|null
$from
the table(s) to be selected from. For example, ['user', 'post']
.
This is used to construct the FROM clause in a SQL statement.
Tags
$groupBy
public
array<string|int, mixed>|null
$groupBy
how to group the query results. For example, ['company', 'department']
.
This is used to construct the GROUP BY clause in a SQL statement.
$having
public
string|array<string|int, mixed>|ExpressionInterface|null
$having
the condition to be applied in the GROUP BY clause. It can be either a string or an array. Please refer to [[where()]] on how to specify the condition.
$indexBy
public
string|callable|null
$indexBy
the name of the column by which the query results should be indexed by. This can also be a callable (e.g. anonymous function) that returns the index value based on the given row data. For more details, see [[indexBy()]]. This property is only used by [[QueryInterface::all()|all()]].
$inverseOf
public
string
$inverseOf
the name of the relation that is the inverse of this relation.
For example, an order has a customer, which means the inverse of the "customer" relation
is the "orders", and the inverse of the "orders" relation is the "customer".
If this property is set, the primary record(s) will be referenced through the specified relation.
For example, $customer->orders[0]->customer
and $customer
will be the same object,
and accessing the customer of an order will not trigger new DB query.
This property is only used in relational context.
Tags
$join
public
array<string|int, mixed>|null
$join
how to join with other tables. Each array element represents the specification of one join which has the following structure:
[$joinType, $tableName, $joinCondition]
For example,
[
['INNER JOIN', 'user', 'user.id = author_id'],
['LEFT JOIN', 'team', 'team.id = team_id'],
]
$joinWith
public
array<string|int, mixed>|null
$joinWith
a list of relations that this query should be joined with
$limit
public
int|ExpressionInterface|null
$limit
maximum number of records to be returned. May be an instance of [[ExpressionInterface]]. If not set or less than 0, it means no limit.
$link
public
array<string|int, mixed>
$link
the columns of the primary and foreign tables that establish a relation. The array keys must be columns of the table for this relation, and the array values must be the corresponding columns from the primary table. Do not prefix or quote the column names as this will be done automatically by Yii. This property is only used in relational context.
$modelClass
public
string
$modelClass
the name of the ActiveRecord class.
$multiple
public
bool
$multiple
whether this query represents a relation to more than one record. This property is only used in relational context. If true, this relation will populate all query results into AR instances using [[Query::all()|all()]]. If false, only the first row of the results will be retrieved using [[Query::one()|one()]].
$offset
public
int|ExpressionInterface|null
$offset
zero-based offset from where the records are to be returned. May be an instance of [[ExpressionInterface]]. If not set or less than 0, it means starting from the beginning.
$on
public
string|array<string|int, mixed>|null
$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.
Tags
$orderBy
public
array<string|int, mixed>|null
$orderBy
how to sort the query results. This is used to construct the ORDER BY clause in a SQL statement. The array keys are the columns to be sorted by, and the array values are the corresponding sort directions which can be either SORT_ASC or SORT_DESC. The array may also contain [[ExpressionInterface]] objects. If that is the case, the expressions will be converted into strings without any change.
$params
public
array<string|int, mixed>|null
$params
= []
list of query parameter values indexed by parameter placeholders.
For example, [':name' => 'Dan', ':age' => 31]
.
$primaryModel
public
ActiveRecord
$primaryModel
the primary model of a relational query. This is used only in lazy loading with dynamic query options.
$queryCacheDependency
public
Dependency|null
$queryCacheDependency
the dependency to be associated with the cached query result for this query
Tags
$queryCacheDuration
public
int|bool|null
$queryCacheDuration
the default number of seconds that query results can remain valid in cache.
Use 0 to indicate that the cached data will never expire.
Use a negative number to indicate that query cache should not be used.
Use boolean true
to indicate that [[Connection::queryCacheDuration]] should be used.
Tags
$select
public
array<string|int, mixed>|null
$select
the columns being selected. For example, ['id', 'name']
.
This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.
Tags
$selectOption
public
string|null
$selectOption
additional option that should be appended to the 'SELECT' keyword. For example, in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
$sql
public
string|null
$sql
the SQL statement to be executed for retrieving AR records. This is set by [[ActiveRecord::findBySql()]].
$tablesUsedInFrom read-only
public
array<string|int, string>
$tablesUsedInFrom
Table names indexed by aliases.
$union
public
array<string|int, mixed>|null
$union
this is used to construct the UNION clause(s) in a SQL statement. Each array element is an array of the following structure:
-
query
: either a string or a [[Query]] object representing a query -
all
: boolean, whether it should beUNION ALL
orUNION
$via
public
array<string|int, mixed>|object
$via
the query associated with the junction table. Please call [[via()]] to set this property instead of directly setting it. This property is only used in relational context.
Tags
$where
public
string|array<string|int, mixed>|ExpressionInterface|null
$where
query condition. This refers to the WHERE clause in a SQL statement.
For example, ['age' => 31, 'team' => 1]
.
Tags
$with
public
array<string|int, mixed>
$with
a list of relations that this query should be performed with
$withQueries
public
array<string|int, mixed>|null
$withQueries
this is used to construct the WITH section in a SQL query. Each array element is an array of the following structure:
-
query
: either a string or a [[Query]] object representing a query -
alias
: string, alias of query for further usage -
recursive
: boolean, whether it should beWITH RECURSIVE
orWITH
Tags
$_behaviors
private
array<string|int, Behavior>|null
$_behaviors
the attached behaviors (behavior name => behavior). This is null
when not initialized.
$_events
private
array<string|int, mixed>
$_events
= []
the attached event handlers (event name => handlers)
$_eventWildcards
private
array<string|int, mixed>
$_eventWildcards
= []
the event handlers attached for wildcard patterns (event name wildcard => handlers)
Tags
$viaMap
private
mixed
$viaMap
Methods
__call()
Calls the named method which is not a class method.
public
__call(string $name, array<string|int, mixed> $params) : mixed
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
Parameters
- $name : string
-
the method name
- $params : array<string|int, mixed>
-
method parameters
Tags
Return values
mixed —the method return value
__clone()
Clones internal objects.
public
__clone() : mixed
__construct()
Constructor.
public
__construct(string $modelClass[, array<string|int, mixed> $config = [] ]) : mixed
Parameters
- $modelClass : string
-
the model class associated with this query
- $config : array<string|int, mixed> = []
-
configurations to be applied to the newly created query object
__get()
Returns the value of a component property.
public
__get(string $name) : mixed
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $component->property;
.
Parameters
- $name : string
-
the property name
Tags
Return values
mixed —the property value or the value of a behavior's property
__isset()
Checks if a property is set, i.e. defined and not null.
public
__isset(string $name) : bool
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
false
for non existing properties
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($component->property)
.
Parameters
- $name : string
-
the property name or the event name
Tags
Return values
bool —whether the named property is set
__set()
Sets the value of a component property.
public
__set(string $name, mixed $value) : mixed
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of "on xyz": attach the handler to the event "xyz"
- a behavior in the format of "as xyz": attach the behavior named as "xyz"
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $component->property = $value;
.
Parameters
- $name : string
-
the property name or the event name
- $value : mixed
-
the property value
Tags
__toString()
Returns the SQL representation of Query
public
__toString() : string
Return values
string__unset()
Sets a component property to be null.
public
__unset(string $name) : mixed
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value to be null
- a property of a behavior: set the property value to be null
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($component->property)
.
Parameters
- $name : string
-
the property name
Tags
addGroupBy()
Adds additional group-by columns to the existing ones.
public
addGroupBy(string|array<string|int, mixed>|ExpressionInterface $columns) : $this
Parameters
- $columns : string|array<string|int, mixed>|ExpressionInterface
-
additional columns to be grouped by. Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression).
Note that if your group-by is an expression containing commas, you should always use an array to represent the group-by information. Otherwise, the method will not be able to correctly determine the group-by columns.
Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL. Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
Tags
Return values
$this —the query object itself
addOrderBy()
Adds additional ORDER BY columns to the query.
public
addOrderBy(string|array<string|int, mixed>|ExpressionInterface $columns) : $this
Parameters
- $columns : string|array<string|int, mixed>|ExpressionInterface
-
the columns (and the directions) to be ordered by. Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array (e.g.
['id' => SORT_ASC, 'name' => SORT_DESC]
).The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression).
Note that if your order-by is an expression containing commas, you should always use an array to represent the order-by information. Otherwise, the method will not be able to correctly determine the order-by columns.
Since version 2.0.7, an [[ExpressionInterface]] object can be passed to specify the ORDER BY part explicitly in plain SQL.
Tags
Return values
$this —the query object itself
addParams()
Adds additional parameters to be bound to the query.
public
addParams(array<string|int, mixed> $params) : $this
Parameters
- $params : array<string|int, mixed>
-
list of query parameter values indexed by parameter placeholders. For example,
[':name' => 'Dan', ':age' => 31]
.
Tags
Return values
$this —the query object itself
addSelect()
Add more columns to the SELECT part of the query.
public
addSelect(string|array<string|int, mixed>|ExpressionInterface $columns) : $this
Note, that if [[select]] has not been specified before, you should include *
explicitly
if you want to select all remaining columns too:
$query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
Parameters
- $columns : string|array<string|int, mixed>|ExpressionInterface
-
the columns to add to the select. See [[select()]] for more details about the format of this parameter.
Tags
Return values
$this —the query object itself
alias()
Define an alias for the table defined in [[modelClass]].
public
alias(string $alias) : $this
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.
Parameters
- $alias : string
-
the table alias.
Tags
Return values
$this —the query object itself
all()
Executes query and returns all results as an array.
public
all([Connection|null $db = null ]) : array<string|int, mixed>|array<string|int, ActiveRecord>
Parameters
- $db : Connection|null = null
-
the DB connection used to create the DB command. If null, the DB connection returned by [[modelClass]] will be used.
Return values
array<string|int, mixed>|array<string|int, ActiveRecord> —the query results. If the query results in nothing, an empty array will be returned.
andFilterCompare()
Adds a filtering condition for a specific column and allow the user to choose a filter operator.
public
andFilterCompare(string $name, string $value[, string $defaultOperator = '=' ]) : $this
It adds an additional WHERE condition for the given field and determines the comparison operator
based on the first few characters of the given value.
The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
The new condition and the existing one will be joined using the AND
operator.
The comparison operator is intelligently determined based on the first few characters in the given value. In particular, it recognizes the following operators if they appear as the leading characters in the given value:
-
<
: the column must be less than the given value. -
>
: the column must be greater than the given value. -
<=
: the column must be less than or equal to the given value. -
>=
: the column must be greater than or equal to the given value. -
<>
: the column must not be the same as the given value. -
=
: the column must be equal to the given value. - If none of the above operators is detected, the
$defaultOperator
will be used.
Parameters
- $name : string
-
the column name.
- $value : string
-
the column value optionally prepended with the comparison operator.
- $defaultOperator : string = '='
-
The operator to use, when no operator is given in
$value
. Defaults to=
, performing an exact match.
Tags
Return values
$this —The query object itself
andFilterHaving()
Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
public
andFilterHaving(array<string|int, mixed> $condition) : $this
The new condition and the existing one will be joined using the AND
operator.
This method is similar to [[andHaving()]]. The main difference is that this method will remove [[isEmpty()|empty query operands]]. As a result, this method is best suited for building query conditions based on filter values entered by users.
Parameters
- $condition : array<string|int, mixed>
-
the new HAVING condition. Please refer to [[having()]] on how to specify this parameter.
Tags
Return values
$this —the query object itself
andFilterWhere()
Adds an additional WHERE condition to the existing one but ignores [[isEmpty()|empty operands]].
public
andFilterWhere(array<string|int, mixed> $condition) : $this
The new condition and the existing one will be joined using the 'AND' operator.
This method is similar to [[andWhere()]]. The main difference is that this method will remove [[isEmpty()|empty query operands]]. As a result, this method is best suited for building query conditions based on filter values entered by users.
Parameters
- $condition : array<string|int, mixed>
-
the new WHERE condition. Please refer to [[where()]] on how to specify this parameter.
Tags
Return values
$this —the query object itself
andHaving()
Adds an additional HAVING condition to the existing one.
public
andHaving(string|array<string|int, mixed>|ExpressionInterface $condition[, array<string|int, mixed> $params = [] ]) : $this
The new condition and the existing one will be joined using the AND
operator.
Parameters
- $condition : string|array<string|int, mixed>|ExpressionInterface
-
the new HAVING condition. Please refer to [[where()]] on how to specify this parameter.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query.
Tags
Return values
$this —the query object itself
andOnCondition()
Adds an additional ON condition to the existing one.
public
andOnCondition(string|array<string|int, mixed> $condition[, array<string|int, mixed> $params = [] ]) : $this
The new condition and the existing one will be joined using the 'AND' operator.
Parameters
- $condition : string|array<string|int, mixed>
-
the new ON condition. Please refer to [[where()]] on how to specify this parameter.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query.
Tags
Return values
$this —the query object itself
andWhere()
Adds an additional WHERE condition to the existing one.
public
andWhere(string|array<string|int, mixed>|ExpressionInterface $condition[, array<string|int, mixed> $params = [] ]) : $this
The new condition and the existing one will be joined using the AND
operator.
Parameters
- $condition : string|array<string|int, mixed>|ExpressionInterface
-
the new WHERE condition. Please refer to [[where()]] on how to specify this parameter.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query.
Tags
Return values
$this —the query object itself
asArray()
Sets the [[asArray]] property.
public
asArray([bool $value = true ]) : $this
Parameters
- $value : bool = true
-
whether to return the query results in terms of arrays instead of Active Records.
Return values
$this —the query object itself
attachBehavior()
Attaches a behavior to this component.
public
attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the [[Behavior::attach()]] method.
Parameters
- $name : string
-
the name of the behavior.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior configuration. This can be one of the following:
- a [[Behavior]] object
- a string specifying the behavior class
- an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
Return values
Behavior —the behavior object
attachBehaviors()
Attaches a list of behaviors to the component.
public
attachBehaviors(array<string|int, mixed> $behaviors) : mixed
Each behavior is indexed by its name and should be a [[Behavior]] object, a string specifying the behavior class, or an configuration array for creating the behavior.
Parameters
- $behaviors : array<string|int, mixed>
-
list of behaviors to be attached to the component
Tags
average()
Returns the average of the specified column values.
public
average(string $q[, Connection|null $db = null ]) : mixed
Parameters
- $q : string
-
the column name or expression. Make sure you properly quote column names in the expression.
- $db : Connection|null = null
-
the database connection used to generate the SQL statement. If this parameter is not given, the
db
application component will be used.
Return values
mixed —the average of the specified column values.
batch()
Starts a batch query.
public
batch([int $batchSize = 100 ][, Connection|null $db = null ]) : BatchQueryResult
A batch query supports fetching data in batches, which can keep the memory usage under a limit. This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface and can be traversed to retrieve the data in batches.
For example,
$query = (new Query)->from('user');
foreach ($query->batch() as $rows) {
// $rows is an array of 100 or fewer rows from user table
}
Parameters
- $batchSize : int = 100
-
the number of records to be fetched in each batch.
- $db : Connection|null = null
-
the database connection. If not set, the "db" application component will be used.
Return values
BatchQueryResult —the batch query result. It implements the [[\Iterator]] interface and can be traversed to retrieve the data in batches.
behaviors()
Returns a list of behaviors that this component should behave as.
public
behaviors() : array<string|int, mixed>
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from [[Behavior]]. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using [[getBehavior()]] or be detached using [[detachBehavior()]]. Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
Return values
array<string|int, mixed> —the behavior configurations.
cache()
Enables query cache for this Query.
public
cache([int|true $duration = true ][, Dependency|null $dependency = null ]) : $this
Parameters
- $duration : int|true = true
-
the number of seconds that query results can remain valid in cache. Use 0 to indicate that the cached data will never expire. Use a negative number to indicate that query cache should not be used. Use boolean
true
to indicate that [[Connection::queryCacheDuration]] should be used. Defaults totrue
. - $dependency : Dependency|null = null
-
the cache dependency associated with the cached result.
Tags
Return values
$this —the Query object itself
canGetProperty()
Returns a value indicating whether a property can be read.
public
canGetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property can be read if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a readable property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be read
canSetProperty()
Returns a value indicating whether a property can be set.
public
canSetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property can be written if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a writable property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be written
className()
Returns the fully qualified name of this class.
public
static className() : string
Tags
Return values
string —the fully qualified name of this class.
column()
Executes the query and returns the first column of the result.
public
column([Connection|null $db = null ]) : array<string|int, mixed>
Parameters
- $db : Connection|null = null
-
the database connection used to generate the SQL statement. If this parameter is not given, the
db
application component will be used.
Return values
array<string|int, mixed> —the first column of the query result. An empty array is returned if the query results in nothing.
count()
Returns the number of records.
public
count([string $q = '*' ][, Connection|null $db = null ]) : int|string|null
Parameters
- $q : string = '*'
-
the COUNT expression. Defaults to '*'. Make sure you properly quote column names in the expression.
- $db : Connection|null = null
-
the database connection used to generate the SQL statement. If this parameter is not given (or null), the
db
application component will be used.
Return values
int|string|null —number of records. The result may be a string depending on the underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
create()
Creates a new Query object and copies its property values from an existing one.
public
static create(Query $from) : Query
The properties being copies are the ones to be used by query builders.
Parameters
- $from : Query
-
the source query object
Return values
Query —the new Query object
createCommand()
Creates a DB command that can be used to execute this query.
public
createCommand([Connection|null $db = null ]) : Command
Parameters
- $db : Connection|null = null
-
the DB connection used to create the DB command. If
null
, the DB connection returned by [[modelClass]] will be used.
Return values
Command —the created DB command instance.
detachBehavior()
Detaches a behavior from the component.
public
detachBehavior(string $name) : Behavior|null
The behavior's [[Behavior::detach()]] method will be invoked.
Parameters
- $name : string
-
the behavior's name.
Return values
Behavior|null —the detached behavior. Null if the behavior does not exist.
detachBehaviors()
Detaches all behaviors from the component.
public
detachBehaviors() : mixed
distinct()
Sets the value indicating whether to SELECT DISTINCT or not.
public
distinct([bool $value = true ]) : $this
Parameters
- $value : bool = true
-
whether to SELECT DISTINCT or not.
Return values
$this —the query object itself
each()
Starts a batch query and retrieves data row by row.
public
each([int $batchSize = 100 ][, Connection|null $db = null ]) : BatchQueryResult
This method is similar to [[batch()]] except that in each iteration of the result, only one row of data is returned. For example,
$query = (new Query)->from('user');
foreach ($query->each() as $row) {
}
Parameters
- $batchSize : int = 100
-
the number of records to be fetched in each batch.
- $db : Connection|null = null
-
the database connection. If not set, the "db" application component will be used.
Return values
BatchQueryResult —the batch query result. It implements the [[\Iterator]] interface and can be traversed to retrieve the data in batches.
emulateExecution()
Sets whether to emulate query execution, preventing any interaction with data storage.
public
emulateExecution([bool $value = true ]) : $this
After this mode is enabled, methods, returning query results like [[QueryInterface::one()]],
[[QueryInterface::all()]], [[QueryInterface::exists()]] and so on, will return empty or false values.
You should use this method in case your program logic indicates query should not return any results, like
in case you set false where condition like 0=1
.
Parameters
- $value : bool = true
-
whether to prevent query execution.
Tags
Return values
$this —the query object itself.
ensureBehaviors()
Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
public
ensureBehaviors() : mixed
exists()
Returns a value indicating whether the query result contains any row of data.
public
exists([Connection|null $db = null ]) : bool
Parameters
- $db : Connection|null = null
-
the database connection used to generate the SQL statement. If this parameter is not given, the
db
application component will be used.
Return values
bool —whether the query result contains any row of data.
filterHaving()
Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
public
filterHaving(array<string|int, mixed> $condition) : $this
This method is similar to [[having()]]. The main difference is that this method will remove [[isEmpty()|empty query operands]]. As a result, this method is best suited for building query conditions based on filter values entered by users.
The following code shows the difference between this method and [[having()]]:
// HAVING `age`=:age
$query->filterHaving(['name' => null, 'age' => 20]);
// HAVING `age`=:age
$query->having(['age' => 20]);
// HAVING `name` IS NULL AND `age`=:age
$query->having(['name' => null, 'age' => 20]);
Note that unlike [[having()]], you cannot pass binding parameters to this method.
Parameters
- $condition : array<string|int, mixed>
-
the conditions that should be put in the HAVING part. See [[having()]] on how to specify this parameter.
Tags
Return values
$this —the query object itself
filterWhere()
Sets the WHERE part of the query but ignores [[isEmpty()|empty operands]].
public
filterWhere(array<string|int, mixed> $condition) : $this
This method is similar to [[where()]]. The main difference is that this method will remove [[isEmpty()|empty query operands]]. As a result, this method is best suited for building query conditions based on filter values entered by users.
The following code shows the difference between this method and [[where()]]:
// WHERE `age`=:age
$query->filterWhere(['name' => null, 'age' => 20]);
// WHERE `age`=:age
$query->where(['age' => 20]);
// WHERE `name` IS NULL AND `age`=:age
$query->where(['name' => null, 'age' => 20]);
Note that unlike [[where()]], you cannot pass binding parameters to this method.
Parameters
- $condition : array<string|int, mixed>
-
the conditions that should be put in the WHERE part. See [[where()]] on how to specify this parameter.
Tags
Return values
$this —the query object itself
findFor()
Finds the related records for the specified primary record.
public
findFor(string $name, ActiveRecordInterface|BaseActiveRecord $model) : mixed
This method is invoked when a relation of an ActiveRecord is being accessed lazily.
Parameters
- $name : string
-
the relation name
- $model : ActiveRecordInterface|BaseActiveRecord
-
the primary model
Tags
Return values
mixed —the related record(s)
findWith()
Finds records corresponding to one or multiple relations and populates them into the primary models.
public
findWith(array<string|int, mixed> $with, array<string|int, mixed>|array<string|int, ActiveRecord> &$models) : mixed
Parameters
- $with : array<string|int, mixed>
-
a list of relations that this query should be performed with. Please refer to [[with()]] for details about specifying this parameter.
- $models : array<string|int, mixed>|array<string|int, ActiveRecord>
-
the primary models (can be either AR instances or arrays)
from()
Sets the FROM part of the query.
public
from(string|array<string|int, mixed>|ExpressionInterface $tables) : $this
Parameters
- $tables : string|array<string|int, mixed>|ExpressionInterface
-
the table(s) to be selected from. This can be either a string (e.g.
'user'
) or an array (e.g.['user', 'profile']
) specifying one or several table names. Table names can contain schema prefixes (e.g.'public.user'
) and/or table aliases (e.g.'user u'
). The method will automatically quote the table names unless it contains some parenthesis (which means the table is given as a sub-query or DB expression).When the tables are specified as an array, you may also use the array keys as the table aliases (if a table does not need alias, do not use a string key).
Use a Query object to represent a sub-query. In this case, the corresponding array key will be used as the alias for the sub-query.
To specify the
FROM
part in plain SQL, you may pass an instance of [[ExpressionInterface]].Here are some examples:
// SELECT * FROM `user` `u`, `profile`; $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']); // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`; $subquery = (new \yii\db\Query)->from('user')->where(['active' => true]) $query = (new \yii\db\Query)->from(['activeusers' => $subquery]); // subquery can also be a string with plain SQL wrapped in parenthesis // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`; $subquery = "(SELECT * FROM `user` WHERE `active` = 1)"; $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
Return values
$this —the query object itself
getBehavior()
Returns the named behavior object.
public
getBehavior(string $name) : Behavior|null
Parameters
- $name : string
-
the behavior name
Return values
Behavior|null —the behavior object, or null if the behavior does not exist
getBehaviors()
Returns all behaviors attached to this component.
public
getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior> —list of behaviors attached to this component
getTablesUsedInFrom()
Returns table names used in [[from]] indexed by aliases.
public
getTablesUsedInFrom() : array<string|int, string>
Tags
Return values
array<string|int, string> —table names indexed by aliases
groupBy()
Sets the GROUP BY part of the query.
public
groupBy(string|array<string|int, mixed>|ExpressionInterface|null $columns) : $this
Parameters
- $columns : string|array<string|int, mixed>|ExpressionInterface|null
-
the columns to be grouped by. Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression).
Note that if your group-by is an expression containing commas, you should always use an array to represent the group-by information. Otherwise, the method will not be able to correctly determine the group-by columns.
Since version 2.0.7, an [[ExpressionInterface]] object can be passed to specify the GROUP BY part explicitly in plain SQL. Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
Tags
Return values
$this —the query object itself
hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public
hasEventHandlers(string $name) : bool
Parameters
- $name : string
-
the event name
Return values
bool —whether there is any handler attached to the event.
hasMethod()
Returns a value indicating whether a method is defined.
public
hasMethod(string $name[, bool $checkBehaviors = true ]) : bool
A method is defined if:
- the class has a method with the specified name
- an attached behavior has a method with the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkBehaviors : bool = true
-
whether to treat behaviors' methods as methods of this component
Return values
bool —whether the method is defined
hasProperty()
Returns a value indicating whether a property is defined for this component.
public
hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property is defined
having()
Sets the HAVING part of the query.
public
having(string|array<string|int, mixed>|ExpressionInterface $condition[, array<string|int, mixed> $params = [] ]) : $this
Parameters
- $condition : string|array<string|int, mixed>|ExpressionInterface
-
the conditions to be put after HAVING. Please refer to [[where()]] on how to specify this parameter.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query.
Tags
Return values
$this —the query object itself
indexBy()
Sets the [[indexBy]] property.
public
indexBy(string|callable $column) : $this
Parameters
- $column : string|callable
-
the name of the column by which the query results should be indexed by. This can also be a callable (e.g. anonymous function) that returns the index value based on the given row data. The signature of the callable should be:
function ($row) { // return the index value corresponding to $row }
Return values
$this —the query object itself
init()
Initializes the object.
public
init() : mixed
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.
innerJoin()
Appends an INNER JOIN part to the query.
public
innerJoin(string|array<string|int, mixed> $table[, string|array<string|int, mixed> $on = '' ][, array<string|int, mixed> $params = [] ]) : $this
Parameters
- $table : string|array<string|int, mixed>
-
the table or sub-query to be joined.
Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression).
You may also specify the table as an array with one element, using the array key as the table alias (e.g. ['u' => 'user']).
To join a sub-query, use an array with one element, with the value set to a [[Query]] object representing the sub-query, and the corresponding key representing the alias.
- $on : string|array<string|int, mixed> = ''
-
the join condition that should appear in the ON part. Please refer to [[join()]] on how to specify this parameter.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query.
Return values
$this —the query object itself
innerJoinWith()
Inner joins with the specified relations.
public
innerJoinWith(string|array<string|int, mixed> $with[, bool|array<string|int, mixed> $eagerLoading = true ]) : $this
This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN". Please refer to [[joinWith()]] for detailed usage of this method.
Parameters
- $with : string|array<string|int, mixed>
-
the relations to be joined with.
- $eagerLoading : bool|array<string|int, mixed> = true
-
whether to eager load the relations. Note, that this does not mean, that the relations are populated from the query result. An extra query will still be performed to bring in the related data.
Tags
Return values
$this —the query object itself
inverseOf()
Sets the name of the relation that is the inverse of this relation.
public
inverseOf(string $relationName) : $this
For example, a customer has orders, which means the inverse of the "orders" relation is the "customer".
If this property is set, the primary record(s) will be referenced through the specified relation.
For example, $customer->orders[0]->customer
and $customer
will be the same object,
and accessing the customer of an order will not trigger a new DB query.
Use this method when declaring a relation in the [[ActiveRecord]] class, e.g. in Customer model:
public function getOrders()
{
return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer');
}
This also may be used for Order model, but with caution:
public function getCustomer()
{
return $this->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders');
}
in this case result will depend on how order(s) was loaded. Let's suppose customer has several orders. If only one order was loaded:
$orders = Order::find()->where(['id' => 1])->all();
$customerOrders = $orders[0]->customer->orders;
variable $customerOrders
will contain only one order. If orders was loaded like this:
$orders = Order::find()->with('customer')->where(['customer_id' => 1])->all();
$customerOrders = $orders[0]->customer->orders;
variable $customerOrders
will contain all orders of the customer.
Parameters
- $relationName : string
-
the name of the relation that is the inverse of this relation.
Return values
$this —the relation object itself.
join()
Appends a JOIN part to the query.
public
join(string $type, string|array<string|int, mixed> $table[, string|array<string|int, mixed> $on = '' ][, array<string|int, mixed> $params = [] ]) : $this
The first parameter specifies what type of join it is.
Parameters
- $type : string
-
the type of join, such as INNER JOIN, LEFT JOIN.
- $table : string|array<string|int, mixed>
-
the table or sub-query to be joined.
Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression).
You may also specify the table as an array with one element, using the array key as the table alias (e.g. ['u' => 'user']).
To join a sub-query, use an array with one element, with the value set to a [[Query]] object representing the sub-query, and the corresponding key representing the alias.
- $on : string|array<string|int, mixed> = ''
-
the join condition that should appear in the ON part. Please refer to [[where()]] on how to specify this parameter.
Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so the following would not work as expected:
['post.author_id' => 'user.id']
, it would match thepost.author_id
column value against the string'user.id'
. It is recommended to use the string syntax here which is more suited for a join:'post.author_id = user.id'
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query.
Return values
$this —the query object itself
joinWith()
Joins with the specified relations.
public
joinWith(string|array<string|int, mixed> $with[, bool|array<string|int, mixed> $eagerLoading = true ][, string|array<string|int, mixed> $joinType = 'LEFT JOIN' ]) : $this
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.
Parameters
- $with : string|array<string|int, mixed>
-
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:
// 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 : bool|array<string|int, mixed> = true
-
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. Note, that this does not mean, that the relations are populated from the query result. An extra query will still be performed to bring in the related data. Defaults totrue
. - $joinType : string|array<string|int, mixed> = 'LEFT JOIN'
-
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 ofrelationName => joinType
to specify different join types for different relations.
Return values
$this —the query object itself
leftJoin()
Appends a LEFT OUTER JOIN part to the query.
public
leftJoin(string|array<string|int, mixed> $table[, string|array<string|int, mixed> $on = '' ][, array<string|int, mixed> $params = [] ]) : $this
Parameters
- $table : string|array<string|int, mixed>
-
the table or sub-query to be joined.
Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression).
You may also specify the table as an array with one element, using the array key as the table alias (e.g. ['u' => 'user']).
To join a sub-query, use an array with one element, with the value set to a [[Query]] object representing the sub-query, and the corresponding key representing the alias.
- $on : string|array<string|int, mixed> = ''
-
the join condition that should appear in the ON part. Please refer to [[join()]] on how to specify this parameter.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query
Return values
$this —the query object itself
limit()
Sets the LIMIT part of the query.
public
limit(int|ExpressionInterface|null $limit) : $this
Parameters
- $limit : int|ExpressionInterface|null
-
the limit. Use null or negative value to disable limit.
Return values
$this —the query object itself
max()
Returns the maximum of the specified column values.
public
max(string $q[, Connection|null $db = null ]) : mixed
Parameters
- $q : string
-
the column name or expression. Make sure you properly quote column names in the expression.
- $db : Connection|null = null
-
the database connection used to generate the SQL statement. If this parameter is not given, the
db
application component will be used.
Return values
mixed —the maximum of the specified column values.
min()
Returns the minimum of the specified column values.
public
min(string $q[, Connection|null $db = null ]) : mixed
Parameters
- $q : string
-
the column name or expression. Make sure you properly quote column names in the expression.
- $db : Connection|null = null
-
the database connection used to generate the SQL statement. If this parameter is not given, the
db
application component will be used.
Return values
mixed —the minimum of the specified column values.
noCache()
Disables query cache for this Query.
public
noCache() : $this
Tags
Return values
$this —the Query object itself
off()
Detaches an existing event handler from this component.
public
off(string $name[, callable|null $handler = null ]) : bool
This method is the opposite of [[on()]].
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
Parameters
- $name : string
-
event name
- $handler : callable|null = null
-
the event handler to be removed. If it is null, all handlers attached to the named event will be removed.
Tags
Return values
bool —if a handler is found and detached
offset()
Sets the OFFSET part of the query.
public
offset(int|ExpressionInterface|null $offset) : $this
Parameters
- $offset : int|ExpressionInterface|null
-
the offset. Use null or negative value to disable offset.
Return values
$this —the query object itself
on()
Attaches an event handler to an event.
public
on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
The event handler must be defined with the following signature,
function ($event)
where $event
is an [[Event]] object which includes parameters associated with the event.
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
Parameters
- $name : string
-
the event name
- $handler : callable
-
the event handler
- $data : mixed = null
-
the data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via [[Event::data]].
- $append : bool = true
-
whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.
Tags
onCondition()
Sets the ON condition for a relational query.
public
onCondition(string|array<string|int, mixed> $condition[, array<string|int, mixed> $params = [] ]) : $this
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:
public function getActiveUsers()
{
return $this->hasMany(User::class, ['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.
Parameters
- $condition : string|array<string|int, mixed>
-
the ON condition. Please refer to [[Query::where()]] on how to specify this parameter.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query.
Return values
$this —the query object itself
one()
Executes query and returns a single row of result.
public
one([Connection|null $db = null ]) : ActiveRecord|array<string|int, mixed>|null
Parameters
- $db : Connection|null = null
-
the DB connection used to create the DB command. If
null
, the DB connection returned by [[modelClass]] will be used.
Return values
ActiveRecord|array<string|int, mixed>|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.
orderBy()
Sets the ORDER BY part of the query.
public
orderBy(string|array<string|int, mixed>|ExpressionInterface|null $columns) : $this
Parameters
- $columns : string|array<string|int, mixed>|ExpressionInterface|null
-
the columns (and the directions) to be ordered by. Columns can be specified in either a string (e.g.
"id ASC, name DESC"
) or an array (e.g.['id' => SORT_ASC, 'name' => SORT_DESC]
).The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression).
Note that if your order-by is an expression containing commas, you should always use an array to represent the order-by information. Otherwise, the method will not be able to correctly determine the order-by columns.
Since version 2.0.7, an [[ExpressionInterface]] object can be passed to specify the ORDER BY part explicitly in plain SQL.
Tags
Return values
$this —the query object itself
orFilterHaving()
Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
public
orFilterHaving(array<string|int, mixed> $condition) : $this
The new condition and the existing one will be joined using the OR
operator.
This method is similar to [[orHaving()]]. The main difference is that this method will remove [[isEmpty()|empty query operands]]. As a result, this method is best suited for building query conditions based on filter values entered by users.
Parameters
- $condition : array<string|int, mixed>
-
the new HAVING condition. Please refer to [[having()]] on how to specify this parameter.
Tags
Return values
$this —the query object itself
orFilterWhere()
Adds an additional WHERE condition to the existing one but ignores [[isEmpty()|empty operands]].
public
orFilterWhere(array<string|int, mixed> $condition) : $this
The new condition and the existing one will be joined using the 'OR' operator.
This method is similar to [[orWhere()]]. The main difference is that this method will remove [[isEmpty()|empty query operands]]. As a result, this method is best suited for building query conditions based on filter values entered by users.
Parameters
- $condition : array<string|int, mixed>
-
the new WHERE condition. Please refer to [[where()]] on how to specify this parameter.
Tags
Return values
$this —the query object itself
orHaving()
Adds an additional HAVING condition to the existing one.
public
orHaving(string|array<string|int, mixed>|ExpressionInterface $condition[, array<string|int, mixed> $params = [] ]) : $this
The new condition and the existing one will be joined using the OR
operator.
Parameters
- $condition : string|array<string|int, mixed>|ExpressionInterface
-
the new HAVING condition. Please refer to [[where()]] on how to specify this parameter.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query.
Tags
Return values
$this —the query object itself
orOnCondition()
Adds an additional ON condition to the existing one.
public
orOnCondition(string|array<string|int, mixed> $condition[, array<string|int, mixed> $params = [] ]) : $this
The new condition and the existing one will be joined using the 'OR' operator.
Parameters
- $condition : string|array<string|int, mixed>
-
the new ON condition. Please refer to [[where()]] on how to specify this parameter.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query.
Tags
Return values
$this —the query object itself
orWhere()
Adds an additional WHERE condition to the existing one.
public
orWhere(string|array<string|int, mixed>|ExpressionInterface $condition[, array<string|int, mixed> $params = [] ]) : $this
The new condition and the existing one will be joined using the OR
operator.
Parameters
- $condition : string|array<string|int, mixed>|ExpressionInterface
-
the new WHERE condition. Please refer to [[where()]] on how to specify this parameter.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query.
Tags
Return values
$this —the query object itself
params()
Sets the parameters to be bound to the query.
public
params(array<string|int, mixed> $params) : $this
Parameters
- $params : array<string|int, mixed>
-
list of query parameter values indexed by parameter placeholders. For example,
[':name' => 'Dan', ':age' => 31]
.
Tags
Return values
$this —the query object itself
populate()
Converts the raw query results into the format as specified by this query.
public
populate(mixed $rows) : array<string|int, mixed>
Parameters
- $rows : mixed
-
the raw query result from database
Return values
array<string|int, mixed> —the converted query result
populateRelation()
Finds the related records and populates them into the primary models.
public
populateRelation(string $name, array<string|int, mixed> &$primaryModels) : array<string|int, mixed>
Parameters
- $name : string
-
the relation name
- $primaryModels : array<string|int, mixed>
-
primary models
Tags
Return values
array<string|int, mixed> —the related models
prepare()
Prepares for building SQL.
public
prepare(mixed $builder) : $this
Parameters
- $builder : mixed
Return values
$this —a prepared query instance which will be used by [[QueryBuilder]] to build the SQL
rightJoin()
Appends a RIGHT OUTER JOIN part to the query.
public
rightJoin(string|array<string|int, mixed> $table[, string|array<string|int, mixed> $on = '' ][, array<string|int, mixed> $params = [] ]) : $this
Parameters
- $table : string|array<string|int, mixed>
-
the table or sub-query to be joined.
Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression).
You may also specify the table as an array with one element, using the array key as the table alias (e.g. ['u' => 'user']).
To join a sub-query, use an array with one element, with the value set to a [[Query]] object representing the sub-query, and the corresponding key representing the alias.
- $on : string|array<string|int, mixed> = ''
-
the join condition that should appear in the ON part. Please refer to [[join()]] on how to specify this parameter.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query
Return values
$this —the query object itself
scalar()
Returns the query result as a scalar value.
public
scalar([Connection|null $db = null ]) : string|int|null|false
The value returned will be the first column in the first row of the query results.
Parameters
- $db : Connection|null = null
-
the database connection used to generate the SQL statement. If this parameter is not given, the
db
application component will be used.
Return values
string|int|null|false —the value of the first column in the first row of the query result. False is returned if the query result is empty.
select()
Sets the SELECT part of the query.
public
select(string|array<string|int, mixed>|ExpressionInterface $columns[, string|null $option = null ]) : $this
Parameters
- $columns : string|array<string|int, mixed>|ExpressionInterface
-
the columns to be selected. Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id"). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression). A DB expression may also be passed in form of an [[ExpressionInterface]] object.
Note that if you are selecting an expression like
CONCAT(first_name, ' ', last_name)
, you should use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.When the columns are specified as an array, you may also use array keys as the column aliases (if a column does not need alias, do not use a string key).
Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column as a
Query
instance representing the sub-query. - $option : string|null = null
-
additional option that should be appended to the 'SELECT' keyword. For example, in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
Return values
$this —the query object itself
sum()
Returns the sum of the specified column values.
public
sum(string $q[, Connection|null $db = null ]) : mixed
Parameters
- $q : string
-
the column name or expression. Make sure you properly quote column names in the expression.
- $db : Connection|null = null
-
the database connection used to generate the SQL statement. If this parameter is not given, the
db
application component will be used.
Return values
mixed —the sum of the specified column values.
trigger()
Triggers an event.
public
trigger(string $name[, Event|null $event = null ]) : mixed
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
Parameters
- $name : string
-
the event name
- $event : Event|null = null
-
the event instance. If not set, a default [[Event]] object will be created.
union()
Appends a SQL statement using UNION operator.
public
union(string|Query $sql[, bool $all = false ]) : $this
Parameters
- $sql : string|Query
-
the SQL statement to be appended using UNION
- $all : bool = false
-
TRUE if using UNION ALL and FALSE if using UNION
Return values
$this —the query object itself
via()
Specifies the relation associated with the junction table.
public
via(string $relationName[, callable|null $callable = null ]) : $this
Use this method to specify a pivot record/table when declaring a relation in the [[ActiveRecord]] class:
class Order extends ActiveRecord
{
public function getOrderItems() {
return $this->hasMany(OrderItem::class, ['order_id' => 'id']);
}
public function getItems() {
return $this->hasMany(Item::class, ['id' => 'item_id'])
->via('orderItems');
}
}
Parameters
- $relationName : string
-
the relation name. This refers to a relation declared in [[primaryModel]].
- $callable : callable|null = null
-
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.
Return values
$this —the relation object itself.
viaTable()
Specifies the junction table for a relational query.
public
viaTable(string $tableName, array<string|int, mixed> $link[, callable|null $callable = null ]) : $this
Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class:
public function getItems()
{
return $this->hasMany(Item::class, ['id' => 'item_id'])
->viaTable('order_item', ['order_id' => 'id']);
}
Parameters
- $tableName : string
-
the name of the junction table.
- $link : array<string|int, mixed>
-
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|null = null
-
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.
Tags
Return values
$this —the query object itself
where()
Sets the WHERE part of the query.
public
where(string|array<string|int, mixed>|ExpressionInterface $condition[, array<string|int, mixed> $params = [] ]) : $this
The method requires a $condition
parameter, and optionally a $params
parameter
specifying the values to be bound to the query.
The $condition
parameter should be either a string (e.g. 'id=1'
) or an array.
Parameters
- $condition : string|array<string|int, mixed>|ExpressionInterface
-
the conditions that should be put in the WHERE part.
- $params : array<string|int, mixed> = []
-
the parameters (name => value) to be bound to the query.
Tags
Return values
$this —the query object itself
with()
Specifies the relations with which this query should be performed.
public
with() : $this
The parameters to this method can be either one or multiple strings, or a single array of relation names and the optional callbacks to customize the relations.
A relation name can refer to a relation defined in [[modelClass]]
or a sub-relation that stands for a relation of a related record.
For example, orders.address
means the address
relation defined
in the model class corresponding to the orders
relation.
The following are some usage examples:
// find customers together with their orders and country
Customer::find()->with('orders', 'country')->all();
// find customers together with their orders and the orders' shipping address
Customer::find()->with('orders.address')->all();
// find customers together with their country and orders of status 1
Customer::find()->with([
'orders' => function (\yii\db\ActiveQuery $query) {
$query->andWhere('status = 1');
},
'country',
])->all();
You can call with()
multiple times. Each call will add relations to the existing ones.
For example, the following two statements are equivalent:
Customer::find()->with('orders', 'country')->all();
Customer::find()->with('orders')->with('country')->all();
Return values
$this —the query object itself
withQuery()
Prepends a SQL statement using WITH syntax.
public
withQuery(string|Query $query, string $alias[, bool $recursive = false ]) : $this
Parameters
- $query : string|Query
-
the SQL statement to be prepended using WITH
- $alias : string
-
query alias in WITH construction
- $recursive : bool = false
-
TRUE if using WITH RECURSIVE and FALSE if using WITH
Tags
Return values
$this —the query object itself
cleanUpTableNames()
Clean up table names and aliases Both aliases and names are enclosed into {{ and }}.
protected
cleanUpTableNames(array<string|int, mixed> $tableNames) : array<string|int, string>
Parameters
- $tableNames : array<string|int, mixed>
-
non-empty array
Tags
Return values
array<string|int, string> —table names indexed by aliases
createModels()
Converts found rows into model instances.
protected
createModels(array<string|int, mixed> $rows) : array<string|int, mixed>|array<string|int, ActiveRecord>
Parameters
- $rows : array<string|int, mixed>
Tags
Return values
array<string|int, mixed>|array<string|int, ActiveRecord>filterCondition()
Removes [[isEmpty()|empty operands]] from the given query condition.
protected
filterCondition(array<string|int, mixed> $condition) : array<string|int, mixed>
Parameters
- $condition : array<string|int, mixed>
-
the original condition
Tags
Return values
array<string|int, mixed> —the condition with [[isEmpty()|empty operands]] removed.
getPrimaryTableName()
protected
getPrimaryTableName() : string
Tags
Return values
string —primary table name
getTableNameAndAlias()
Returns the table name and the table alias for [[modelClass]].
protected
getTableNameAndAlias() : array<string|int, mixed>
Tags
Return values
array<string|int, mixed> —the table name and the table alias.
getUnaliasedColumnsFromSelect()
protected
getUnaliasedColumnsFromSelect() : array<string|int, mixed>
Tags
Return values
array<string|int, mixed> —List of columns without aliases from SELECT statement.
getUniqueColumns()
Returns unique column names excluding duplicates.
protected
getUniqueColumns(array<string|int, mixed> $columns) : mixed
Columns to be removed:
- if column definition already present in SELECT part with same alias
- if column definition without alias already present in SELECT part without alias too
Parameters
- $columns : array<string|int, mixed>
-
the columns to be merged to the select.
Tags
isEmpty()
Returns a value indicating whether the give value is "empty".
protected
isEmpty(mixed $value) : bool
The value is considered "empty", if one of the following conditions is satisfied:
- it is
null
, - an empty string (
''
), - a string containing only whitespace characters,
- or an empty array.
Parameters
- $value : mixed
Return values
bool —if the value is empty
normalizeOrderBy()
Normalizes format of ORDER BY data.
protected
normalizeOrderBy(array<string|int, mixed>|string|ExpressionInterface|null $columns) : array<string|int, mixed>
Parameters
- $columns : array<string|int, mixed>|string|ExpressionInterface|null
-
the columns value to normalize. See [[orderBy]] and [[addOrderBy]].
Return values
array<string|int, mixed>normalizeSelect()
Normalizes the SELECT columns passed to [[select()]] or [[addSelect()]].
protected
normalizeSelect(string|array<string|int, mixed>|ExpressionInterface $columns) : array<string|int, mixed>
Parameters
- $columns : string|array<string|int, mixed>|ExpressionInterface
Tags
Return values
array<string|int, mixed>queryScalar()
Queries a scalar value by setting [[select]] first.
protected
queryScalar(mixed $selectExpression, mixed $db) : bool|string|null
Parameters
- $selectExpression : mixed
- $db : mixed
-
the database connection used to execute the query.
Return values
bool|string|nullsetCommandCache()
Sets $command cache, if this query has enabled caching.
protected
setCommandCache(Command $command) : Command
Parameters
- $command : Command
Tags
Return values
CommandaddInverseRelations()
If applicable, populate the query's primary model into the related records' inverse relationship.
private
addInverseRelations(array<string|int, mixed> &$result) : mixed
Parameters
- $result : array<string|int, mixed>
-
the array of related records as generated by [[populate()]]
Tags
attachBehaviorInternal()
Attaches a behavior to this component.
private
attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
- $name : string|int
-
the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior to be attached
Return values
Behavior —the attached behavior.
buildBuckets()
private
buildBuckets(array<string|int, mixed> $models, array<string|int, mixed> $link[, array<string|int, mixed>|null $viaModels = null ][, self|null $viaQuery = null ][, bool $checkMultiple = true ]) : array<string|int, mixed>
Parameters
- $models : array<string|int, mixed>
- $link : array<string|int, mixed>
- $viaModels : array<string|int, mixed>|null = null
- $viaQuery : self|null = null
- $checkMultiple : bool = true
Return values
array<string|int, mixed>buildJoinWith()
private
buildJoinWith() : mixed
ensureNameQuoted()
Ensures name is wrapped with {{ and }}
private
ensureNameQuoted(string $name) : string
Parameters
- $name : string
Return values
stringfilterByModels()
private
filterByModels(array<string|int, mixed> $models) : mixed
Parameters
- $models : array<string|int, mixed>
findJunctionRows()
private
findJunctionRows(array<string|int, mixed> $primaryModels) : array<string|int, mixed>
Parameters
- $primaryModels : array<string|int, mixed>
-
either array of AR instances or arrays
Return values
array<string|int, mixed>getJoinType()
Returns the join type based on the given join type parameter and the relation name.
private
getJoinType(string|array<string|int, mixed> $joinType, string $name) : string
Parameters
- $joinType : string|array<string|int, mixed>
-
the given join type(s)
- $name : string
-
relation name
Return values
string —the real join type
getModelKey()
private
getModelKey(ActiveRecordInterface|array<string|int, mixed> $model, array<string|int, mixed> $attributes) : string|false
Parameters
- $model : ActiveRecordInterface|array<string|int, mixed>
- $attributes : array<string|int, mixed>
Return values
string|falseindexBuckets()
Indexes buckets by column name.
private
indexBuckets(array<string|int, mixed> $buckets, string|callable $indexBy) : array<string|int, mixed>
Parameters
- $buckets : array<string|int, mixed>
- $indexBy : string|callable
-
the name of the column by which the query results should be indexed by. This can also be a callable (e.g. anonymous function) that returns the index value based on the given row data.
Return values
array<string|int, mixed>joinWithRelation()
Joins a parent query with a child query.
private
joinWithRelation(ActiveQuery $parent, ActiveQuery $child, string $joinType) : mixed
The current query object will be modified accordingly.
Parameters
- $parent : ActiveQuery
- $child : ActiveQuery
- $joinType : string
joinWithRelations()
Modifies the current query by adding join fragments based on the given relations.
private
joinWithRelations(ActiveRecord $model, array<string|int, mixed> $with, string|array<string|int, mixed> $joinType) : mixed
Parameters
- $model : ActiveRecord
-
the primary model
- $with : array<string|int, mixed>
-
the relations to be joined
- $joinType : string|array<string|int, mixed>
-
the join type
mapVia()
private
mapVia(array<string|int, mixed> $map, array<string|int, mixed> $viaMap) : array<string|int, mixed>
Parameters
- $map : array<string|int, mixed>
- $viaMap : array<string|int, mixed>
Return values
array<string|int, mixed>normalizeModelKey()
private
normalizeModelKey(mixed $value) : string
Parameters
- $value : mixed
-
raw key value. Since 2.0.40 non-string values must be convertible to string (like special objects for cross-DBMS relations, for example:
|MongoId
).
Return values
string —normalized key value.
normalizeRelations()
private
normalizeRelations(ActiveRecord $model, array<string|int, mixed> $with) : array<string|int, ActiveQueryInterface>
Parameters
- $model : ActiveRecord
- $with : array<string|int, mixed>
Return values
array<string|int, ActiveQueryInterface>populateInverseRelation()
private
populateInverseRelation(array<string|int, ActiveRecordInterface> &$primaryModels, array<string|int, ActiveRecordInterface> $models, string $primaryName, string $name) : mixed
Parameters
- $primaryModels : array<string|int, ActiveRecordInterface>
-
primary models
- $models : array<string|int, ActiveRecordInterface>
-
models
- $primaryName : string
-
the primary relation name
- $name : string
-
the relation name
prefixKeyColumns()
private
prefixKeyColumns(array<string|int, mixed> $attributes) : array<string|int, mixed>
Parameters
- $attributes : array<string|int, mixed>
-
the attributes to prefix
Return values
array<string|int, mixed>removeDuplicatedModels()
Removes duplicated models by checking their primary key values.
private
removeDuplicatedModels(array<string|int, mixed> $models) : array<string|int, mixed>
This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
Parameters
- $models : array<string|int, mixed>
-
the models to be checked
Tags
Return values
array<string|int, mixed> —the distinctive models