HumHub Documentation (unofficial)

ActiveQuery extends Component
in package
implements ActiveQueryInterface uses QueryTrait, ActiveQueryTrait, ActiveRelationTrait

ActiveQuery represents a query associated with an Active Record class.

An ActiveQuery can be a normal query or be used in a relational context.

ActiveQuery instances are usually created by [[ActiveRecord::find()]]. Relational queries are created by [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]].

Normal Query

ActiveQuery mainly provides the following methods to retrieve the query results:

  • [[one()]]: returns a single record populated with the first row of data.
  • [[all()]]: returns all records based on the query results.
  • [[count()]]: returns the number of records.
  • [[sum()]]: returns the sum over the specified column.
  • [[average()]]: returns the average over the specified column.
  • [[min()]]: returns the min over the specified column.
  • [[max()]]: returns the max over the specified column.
  • [[scalar()]]: returns the value of the first column in the first row of the query result.
  • [[exists()]]: returns a value indicating whether the query result has data or not.

You can use query methods, such as [[where()]], [[limit()]] and [[orderBy()]] to customize the query options.

ActiveQuery also provides the following additional query options:

  • [[with()]]: list of relations that this query should be performed with.
  • [[indexBy()]]: the name of the column by which the query result should be indexed.
  • [[asArray()]]: whether to return each record as an array.

These options can be configured using methods of the same name. For example:

$customers = Customer::find()->with('orders')->asArray()->all();

Relational query

In relational context ActiveQuery represents a relation between two Active Record classes.

Relational ActiveQuery instances are usually created by calling [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining a getter method which calls one of the above methods and returns the created ActiveQuery object.

A relation is specified by [[link]] which represents the association between columns of different tables; and the multiplicity of the relation is indicated by [[multiple]].

If a relation involves a junction table, it may be specified by [[via()]]. This methods may only be called in a relational context. Same is true for [[inverseOf()]], which marks a relation as inverse of another relation.

Tags
author

Carsten Brandt mail@cebe.cc

since
2.0

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>
$emulateExecution  : bool
$indexBy  : string|callable|null
$inverseOf  : string
$limit  : int|ExpressionInterface|null
$link  : array<string|int, mixed>
$modelClass  : string
$multiple  : bool
$offset  : int|ExpressionInterface|null
$orderBy  : array<string|int, mixed>|null
$primaryModel  : ActiveRecord
$via  : array<string|int, mixed>|object
$where  : string|array<string|int, mixed>|ExpressionInterface|null
$with  : array<string|int, mixed>
$_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.
__unset()  : mixed
Sets a component property to be null.
addOrderBy()  : $this
Adds additional ORDER BY columns to the query.
all()  : array<string|int, mixed>|array<string|int, ActiveRecord>
Executes the query and returns all results as an array.
andFilterWhere()  : $this
Adds an additional WHERE condition to the existing one but ignores [[isEmpty()|empty operands]].
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()  : int
Returns the average of the specified column values.
behaviors()  : array<string|int, mixed>
Returns a list of behaviors that this component should behave as.
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
Returns the number of records.
detachBehavior()  : Behavior|null
Detaches a behavior from the component.
detachBehaviors()  : mixed
Detaches all behaviors from the component.
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.
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.
getBehavior()  : Behavior|null
Returns the named behavior object.
getBehaviors()  : array<string|int, Behavior>
Returns all behaviors attached to this component.
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.
indexBy()  : $this
Sets the [[indexBy]] property.
init()  : mixed
Initializes the object.
inverseOf()  : $this
Sets the name of the relation that is the inverse of this relation.
limit()  : $this
Sets the LIMIT part of the query.
max()  : int
Returns the maximum of the specified column values.
min()  : int
Returns the minimum of the specified column values.
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.
one()  : ActiveRecord|array<string|int, mixed>|null
Executes the query and returns a single row of result.
orderBy()  : $this
Sets the ORDER BY part of the query.
orFilterWhere()  : $this
Adds an additional WHERE condition to the existing one but ignores [[isEmpty()|empty operands]].
orWhere()  : $this
Adds an additional WHERE condition to the existing one.
populateRelation()  : array<string|int, mixed>
Finds the related records and populates them into the primary models.
scalar()  : string
Returns the query result as a scalar value.
sum()  : int
Returns the number of records.
trigger()  : mixed
Triggers an event.
via()  : $this
Specifies the relation associated with the junction table.
where()  : $this
Sets the WHERE part of the query.
with()  : $this
Specifies the relations with which this query should be performed.
createModels()  : array<string|int, mixed>|array<string|int, ActiveRecord>
Converts found rows into model instances.
executeScript()  : array<string|int, mixed>|bool|null|string
Executes a script created by [[LuaScriptBuilder]]
filterCondition()  : array<string|int, mixed>
Removes [[isEmpty()|empty operands]] from the given query condition.
isEmpty()  : bool
Returns a value indicating whether the give value is "empty".
normalizeOrderBy()  : array<string|int, mixed>
Normalizes format of ORDER BY data.
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>
filterByModels()  : mixed
findByPk()  : array<string|int, mixed>|bool|null|string
Fetch by pk if possible as this is much faster
findJunctionRows()  : array<string|int, mixed>
getModelKey()  : string|false
indexBuckets()  : array<string|int, mixed>
Indexes buckets by column name.
mapVia()  : array<string|int, mixed>
normalizeModelKey()  : string
normalizeRelations()  : array<string|int, ActiveQueryInterface>
populateInverseRelation()  : mixed
prefixKeyColumns()  : array<string|int, mixed>

Constants

EVENT_INIT

public mixed EVENT_INIT = 'init'
Tags
event

Event an event that is triggered when the query is initialized via [[init()]].

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.

$emulateExecution

public bool $emulateExecution = false

whether to emulate the actual query execution, returning empty or false results.

Tags
see
emulateExecution()
since
2.0.11

$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
see
inverseOf()

$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.

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.

$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.

$primaryModel

public ActiveRecord $primaryModel

the primary model of a relational query. This is used only in lazy loading with dynamic query options.

$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
see
via()

$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
see
where()

for valid syntax on specifying this value.

$with

public array<string|int, mixed> $with

a list of relations that this query should be performed with

$_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
since
2.0.14

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
throws
UnknownMethodException

when calling unknown method

Return values
mixed

the method return value

__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
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is write-only.

see
__set()
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
see
https://www.php.net/manual/en/function.isset.php
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
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is read-only.

see
__get()

__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
throws
InvalidCallException

if the property is read only.

see
https://www.php.net/manual/en/function.unset.php

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
see
orderBy()
Return values
$this

the query object itself

all()

Executes the query and returns all results as an array.

public all([Connection $db = null ]) : array<string|int, mixed>|array<string|int, ActiveRecord>
Parameters
$db : Connection = null

the database connection used to execute the query. If this parameter is not given, the db application component 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.

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
see
filterWhere()
see
orFilterWhere()
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) : $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.

Tags
see
where()
see
orWhere()
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
see
detachBehavior()
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
see
attachBehavior()

average()

Returns the average of the specified column values.

public average(string $column[, Connection $db = null ]) : int
Parameters
$column : string

the column name or expression. Make sure you properly quote column names in the expression.

$db : Connection = null

the database connection used to execute the query. If this parameter is not given, the db application component will be used.

Return values
int

the average of the specified column values.

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.

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
see
canSetProperty()
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
see
canGetProperty()
Return values
bool

whether the property can be written

className()

Returns the fully qualified name of this class.

public static className() : string
Tags
deprecated

since 2.0.14. On PHP >=5.5, use ::class instead.

Return values
string

the fully qualified name of this class.

column()

Executes the query and returns the first column of the result.

public column(string $column[, Connection $db = null ]) : array<string|int, mixed>
Parameters
$column : string

name of the column to select

$db : Connection = null

the database connection used to execute the query. 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 $db = null ]) : int
Parameters
$q : string = '*'

the COUNT expression. This parameter is ignored by this implementation.

$db : Connection = null

the database connection used to execute the query. If this parameter is not given, the db application component will be used.

Return values
int

number of records

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

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
since
2.0.11
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 $db = null ]) : bool
Parameters
$db : Connection = null

the database connection used to execute the query. 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.

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
see
where()
see
andFilterWhere()
see
orFilterWhere()
Return values
$this

the query object itself

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)

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

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
see
canGetProperty()
see
canSetProperty()
Return values
bool

whether the property is defined

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.

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.

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 $column[, Connection $db = null ]) : int
Parameters
$column : string

the column name or expression. Make sure you properly quote column names in the expression.

$db : Connection = null

the database connection used to execute the query. If this parameter is not given, the db application component will be used.

Return values
int

the maximum of the specified column values.

min()

Returns the minimum of the specified column values.

public min(string $column[, Connection $db = null ]) : int
Parameters
$column : string

the column name or expression. Make sure you properly quote column names in the expression.

$db : Connection = null

the database connection used to execute the query. If this parameter is not given, the db application component will be used.

Return values
int

the minimum of the specified column values.

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
see
on()
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
see
off()

one()

Executes the query and returns a single row of result.

public one([Connection $db = null ]) : ActiveRecord|array<string|int, mixed>|null
Parameters
$db : Connection = null

the database connection used to execute the query. If this parameter is not given, the db application component 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
see
addOrderBy()
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
see
filterWhere()
see
andFilterWhere()
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) : $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.

Tags
see
where()
see
andWhere()
Return values
$this

the query object itself

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
throws
InvalidConfigException

if [[link]] is invalid

Return values
array<string|int, mixed>

the related models

scalar()

Returns the query result as a scalar value.

public scalar(string $attribute[, Connection $db = null ]) : string

The value returned will be the specified attribute in the first record of the query results.

Parameters
$attribute : string

name of the attribute to select

$db : Connection = null

the database connection used to execute the query. If this parameter is not given, the db application component will be used.

Return values
string

the value of the specified attribute in the first record of the query result. Null is returned if the query result is empty.

sum()

Returns the number of records.

public sum(string $column[, Connection $db = null ]) : int
Parameters
$column : string

the column to sum up

$db : Connection = null

the database connection used to execute the query. If this parameter is not given, the db application component will be used.

Return values
int

number of records

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.

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.

where()

Sets the WHERE part of the query.

public where(string|array<string|int, mixed>|ExpressionInterface $condition) : $this

See [[QueryInterface::where()]] for detailed documentation.

Parameters
$condition : string|array<string|int, mixed>|ExpressionInterface

the conditions that should be put in the WHERE part.

Tags
see
andWhere()
see
orWhere()
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

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
since
2.0.11
Return values
array<string|int, mixed>|array<string|int, ActiveRecord>

executeScript()

Executes a script created by [[LuaScriptBuilder]]

protected executeScript(Connection|null $db, string $type[, string $columnName = null ]) : array<string|int, mixed>|bool|null|string
Parameters
$db : Connection|null

the database connection used to execute the query. If this parameter is not given, the db application component will be used.

$type : string

the type of the script to generate

$columnName : string = null
Tags
throws
NotSupportedException
Return values
array<string|int, mixed>|bool|null|string

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
throws
NotSupportedException

if the condition operator is not supported

Return values
array<string|int, mixed>

the condition with [[isEmpty()|empty operands]] removed.

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>

addInverseRelations()

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
since
2.0.9

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>

filterByModels()

private filterByModels(array<string|int, mixed> $models) : mixed
Parameters
$models : array<string|int, mixed>

findByPk()

Fetch by pk if possible as this is much faster

private findByPk(Connection $db, string $type[, string $columnName = null ]) : array<string|int, mixed>|bool|null|string
Parameters
$db : Connection

the database connection used to execute the query. If this parameter is not given, the db application component will be used.

$type : string

the type of the script to generate

$columnName : string = null
Tags
throws
InvalidParamException
throws
NotSupportedException
Return values
array<string|int, mixed>|bool|null|string

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>

indexBuckets()

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>

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.

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>

        
On this page

Search results