Craft 3 Class Reference

Class craft\elements\db\ElementQuery

Inheritance
craft\elements\db\ElementQuery » craft\db\Query » yii\db\Query » yii\base\Component » yii\base\BaseObject
Implements
craft\elements\db\ElementQueryInterface, yii\base\Configurable, yii\db\ExpressionInterface, yii\db\QueryInterface
Uses Traits
yii\base\ArrayableTrait, yii\db\QueryTrait
Subclasses
craft\elements\db\AssetQuery, craft\elements\db\CategoryQuery, craft\elements\db\EntryQuery, craft\elements\db\GlobalSetQuery, craft\elements\db\MatrixBlockQuery, craft\elements\db\TagQuery, craft\elements\db\UserQuery
Available since version
3.0
Source Code
https://github.com/craftcms/cms/blob/master/src/elements/db/ElementQuery.php

ElementQuery represents a SELECT SQL statement for elements in a way that is independent of DBMS.

Public Properties
Property Type Description Defined By
$ancestorDist integer, null The maximum number of levels that results may be separated from ancestorOf(). craft\elements\db\ElementQuery
$ancestorOf integer, craft\base\ElementInterface, null The element (or its ID) that results must be an ancestor of. craft\elements\db\ElementQuery
$archived boolean Whether to return only archived elements. craft\elements\db\ElementQuery
$asArray boolean Whether to return each element as an array. craft\elements\db\ElementQuery
$contentTable string, null The content table that will be joined by this query. craft\elements\db\ElementQuery
$customFields craft\base\FieldInterface[], null The fields that may be involved in this query. craft\elements\db\ElementQuery
$dateCreated mixed When the resulting elements must have been created. craft\elements\db\ElementQuery
$dateUpdated mixed When the resulting elements must have been last updated. craft\elements\db\ElementQuery
$descendantDist integer, null The maximum number of levels that results may be separated from descendantOf(). craft\elements\db\ElementQuery
$descendantOf integer, craft\base\ElementInterface, null The element (or its ID) that results must be a descendant of. craft\elements\db\ElementQuery
$distinct boolean Whether to select distinct rows of data only. yii\db\Query
$elementType string, null The name of the craft\base\ElementInterface class. craft\elements\db\ElementQuery
$emulateExecution boolean Whether to emulate the actual query execution, returning empty or false results. yii\db\QueryTrait
$enabledForSite boolean Whether the elements must be enabled for the chosen site. craft\elements\db\ElementQuery
$fixedOrder boolean Whether results should be returned in the order specified by id(). craft\elements\db\ElementQuery
$from array The table(s) to be selected from. yii\db\Query
$groupBy array How to group the query results. yii\db\Query
$having string, array, yii\db\ExpressionInterface The condition to be applied in the GROUP BY clause. yii\db\Query
$id integer, integer[], false, null The element ID(s). craft\elements\db\ElementQuery
$inReverse boolean Whether the results should be queried in reverse. craft\elements\db\ElementQuery
$indexBy string, callable The name of the column by which the query results should be indexed by. yii\db\QueryTrait
$join array How to join with other tables. yii\db\Query
$level mixed The element’s level within the structure craft\elements\db\ElementQuery
$limit integer, yii\db\ExpressionInterface Maximum number of records to be returned. yii\db\QueryTrait
$nextSiblingOf integer, craft\base\ElementInterface, null The element (or its ID) that the result must be the next sibling of. craft\elements\db\ElementQuery
$offset integer, yii\db\ExpressionInterface Zero-based offset from where the records are to be returned. yii\db\QueryTrait
$orderBy array How to sort the query results. craft\elements\db\ElementQuery
$params array List of query parameter values indexed by parameter placeholders. yii\db\Query
$positionedAfter integer, craft\base\ElementInterface, null The element (or its ID) that the results must be positioned after. craft\elements\db\ElementQuery
$positionedBefore integer, craft\base\ElementInterface, null The element (or its ID) that the results must be positioned before. craft\elements\db\ElementQuery
$prevSiblingOf integer, craft\base\ElementInterface, null The element (or its ID) that the result must be the previous sibling of. craft\elements\db\ElementQuery
$query craft\db\Query, null The query object created by prepare() craft\elements\db\ElementQuery
$queryCacheDependency yii\caching\Dependency The dependency to be associated with the cached query result for this query yii\db\Query
$queryCacheDuration integer, true The default number of seconds that query results can remain valid in cache. yii\db\Query
$ref string, string[], null The reference code(s) used to identify the element(s). craft\elements\db\ElementQuery
$relatedTo integer, array, craft\base\ElementInterface, null The element relation criteria. craft\elements\db\ElementQuery
$search string, array, craft\search\SearchQuery, null The search term to filter the resulting elements by. craft\elements\db\ElementQuery
$select array The columns being selected. yii\db\Query
$selectOption string Additional option that should be appended to the 'SELECT' keyword. yii\db\Query
$siblingOf integer, craft\base\ElementInterface, null The element (or its ID) that the results must be a sibling of. craft\elements\db\ElementQuery
$siteId integer, null The site ID that the elements should be returned in. craft\elements\db\ElementQuery
$slug string, string[], null The slug that resulting elements must have. craft\elements\db\ElementQuery
$status string, string[], null The status(es) that the resulting elements must have. craft\elements\db\ElementQuery
$structureId integer, false, null The structure ID that should be used to join in the structureelements table. craft\elements\db\ElementQuery
$subQuery craft\db\Query, null The subselect’s query object created by prepare() craft\elements\db\ElementQuery
$title string, string[], null The title that resulting elements must have. craft\elements\db\ElementQuery
$uid string, string[], null The element UID(s). craft\elements\db\ElementQuery
$union array This is used to construct the UNION clause(s) in a SQL statement. yii\db\Query
$uri string, string[], null The URI that the resulting element must have. craft\elements\db\ElementQuery
$where string, array Query condition. yii\db\QueryTrait
$with string, array, null The eager-loading declaration craft\elements\db\ElementQuery
$withStructure boolean, null Whether element structure data should automatically be left-joined into the query. craft\elements\db\ElementQuery
Protected Properties
Property Type Description Defined By
$defaultOrderBy array The default orderBy() value to use if orderBy() is empty but not null. craft\elements\db\ElementQuery
Public Methods
Method Description Defined By
__call() Calls the named method which is not a class method. craft\elements\db\ElementQuery
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor craft\elements\db\ElementQuery
__get() Returns the value of a component property. craft\elements\db\ElementQuery
__isset() Checks if a property is set, i.e. defined and not null. craft\elements\db\ElementQuery
__set() Sets the value of a component property. craft\elements\db\ElementQuery
__toString() Returns the SQL representation of Query yii\db\Query
__unset() Sets an object property to null. yii\base\BaseObject
addGroupBy() Adds additional group-by columns to the existing ones. yii\db\Query
addOrderBy() Adds additional ORDER BY columns to the query. craft\elements\db\ElementQuery
addParams() Adds additional parameters to be bound to the query. yii\db\Query
addSelect() Add more columns to the SELECT part of the query. yii\db\Query
all() Executes the query and returns all results as an array. craft\elements\db\ElementQuery
ancestorDist() Sets the ancestorDist() property. craft\elements\db\ElementQuery
ancestorOf() Sets the ancestorOf() property. craft\elements\db\ElementQuery
andFilterCompare() Adds a filtering condition for a specific column and allow the user to choose a filter operator. yii\db\Query
andFilterHaving() Adds an additional HAVING condition to the existing one but ignores empty operands. yii\db\Query
andFilterWhere() Adds an additional WHERE condition to the existing one but ignores empty operands. yii\db\QueryTrait
andHaving() Adds an additional HAVING condition to the existing one. yii\db\Query
andWhere() Adds an additional WHERE condition to the existing one. yii\db\QueryTrait
archived() Sets the archived() property. craft\elements\db\ElementQuery
asArray() Sets the asArray() property. craft\elements\db\ElementQuery
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
average() Returns the average of the specified column values. yii\db\Query
batch() Starts a batch query. yii\db\Query
behaviors() Returns a list of behaviors that this component should behave as. craft\elements\db\ElementQuery
cache() Enables query cache for this Query. yii\db\Query
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
column() Executes the query and returns the first column of the result. craft\db\Query
count() Returns the number of records. craft\elements\db\ElementQuery
create() Creates a new Query object and copies its property values from an existing one. yii\db\Query
createCommand() Creates a DB command that can be used to execute this query. yii\db\Query
criteriaAttributes() Returns the query's criteria attributes. craft\elements\db\ElementQuery
dateCreated() Sets the dateCreated() property. craft\elements\db\ElementQuery
dateUpdated() Sets the dateUpdated() property. craft\elements\db\ElementQuery
descendantDist() Sets the descendantDist() property. craft\elements\db\ElementQuery
descendantOf() Sets the descendantOf() property. craft\elements\db\ElementQuery
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
distinct() Sets the value indicating whether to SELECT DISTINCT or not. yii\db\Query
each() Starts a batch query and retrieves data row by row. yii\db\Query
emulateExecution() Sets whether to emulate query execution, preventing any interaction with data storage. yii\db\QueryTrait
enabledForSite() Sets the enabledForSite() property. craft\elements\db\ElementQuery
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
exists() Returns a value indicating whether the query result contains any row of data. craft\db\Query
extraFields() Returns the list of fields that can be expanded further and returned by toArray(). yii\base\ArrayableTrait
fields() Returns the list of fields that should be returned by default by toArray() when no specific fields are specified. craft\elements\db\ElementQuery
filterHaving() Sets the HAVING part of the query but ignores empty operands. yii\db\Query
filterWhere() Sets the WHERE part of the query but ignores empty operands. yii\db\QueryTrait
find() Returns all elements that match the criteria. craft\elements\db\ElementQuery
first() Returns the first element that matches the criteria. craft\elements\db\ElementQuery
fixedOrder() Sets the fixedOrder() property. craft\elements\db\ElementQuery
from() Sets the FROM part of the query. yii\db\Query
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getCachedResult() Returns the resulting elements set by setCachedResult(), if the criteria params haven’t changed since then. craft\elements\db\ElementQuery
getCriteria() Returns an array of the current criteria attribute values. craft\elements\db\ElementQuery
getIterator() Required by the IteratorAggregate interface. craft\elements\db\ElementQuery
getRawSql() Shortcut for createCommand()->getRawSql(). craft\db\Query
getTablesUsedInFrom() Returns table names used in from() indexed by aliases. yii\db\Query
groupBy() Sets the GROUP BY part of the query. yii\db\Query
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
having() Sets the HAVING part of the query. yii\db\Query
id() Sets the id() property. craft\elements\db\ElementQuery
ids() Executes the query and returns the IDs of the resulting elements. craft\elements\db\ElementQuery
inReverse() Sets the inReverse() property. craft\elements\db\ElementQuery
indexBy() Sets the indexBy() property. yii\db\QueryTrait
init() Initializes the object. craft\db\Query
innerJoin() Appends an INNER JOIN part to the query. yii\db\Query
isJoined() Returns whether a given table has been joined in this query. craft\db\Query
join() Appends a JOIN part to the query. yii\db\Query
last() Returns the last element that matches the criteria. craft\elements\db\ElementQuery
leftJoin() Appends a LEFT OUTER JOIN part to the query. yii\db\Query
level() Sets the level() property. craft\elements\db\ElementQuery
limit() Sets the LIMIT part of the query. yii\db\QueryTrait
locale() Sets the site() property. craft\elements\db\ElementQuery
localeEnabled() Sets the enabledForSite() property. craft\elements\db\ElementQuery
max() Returns the maximum of the specified column values. yii\db\Query
min() Returns the minimum of the specified column values. yii\db\Query
nextSiblingOf() Sets the nextSiblingOf() property. craft\elements\db\ElementQuery
noCache() Disables query cache for this Query. yii\db\Query
nth() Executes the query and returns a single row of result at a given offset. craft\elements\db\ElementQuery
off() Detaches an existing event handler from this component. yii\base\Component
offset() Sets the OFFSET part of the query. yii\db\QueryTrait
offsetExists() Required by the ArrayAccess interface. craft\elements\db\ElementQuery
offsetGet() Required by the ArrayAccess interface. craft\elements\db\ElementQuery
offsetSet() Required by the ArrayAccess interface. craft\elements\db\ElementQuery
offsetUnset() Required by the ArrayAccess interface. craft\elements\db\ElementQuery
on() Attaches an event handler to an event. yii\base\Component
one() Executes the query and returns a single row of result. craft\elements\db\ElementQuery
orFilterHaving() Adds an additional HAVING condition to the existing one but ignores empty operands. yii\db\Query
orFilterWhere() Adds an additional WHERE condition to the existing one but ignores empty operands. yii\db\QueryTrait
orHaving() Adds an additional HAVING condition to the existing one. yii\db\Query
orWhere() Adds an additional WHERE condition to the existing one. yii\db\QueryTrait
order() Sets the orderBy() property. craft\elements\db\ElementQuery
orderBy() Sets the ORDER BY part of the query. yii\db\QueryTrait
pairs() Executes the query and returns the first two columns in the results as key/value pairs. craft\db\Query
params() Sets the parameters to be bound to the query. yii\db\Query
populate() Converts the raw query results into the format as specified by this query. craft\elements\db\ElementQuery
positionedAfter() Sets the positionedAfter() property. craft\elements\db\ElementQuery
positionedBefore() Sets the positionedBefore() property. craft\elements\db\ElementQuery
prepare() Prepares for building SQL. craft\elements\db\ElementQuery
prevSiblingOf() Sets the prevSiblingOf() property. craft\elements\db\ElementQuery
ref() Sets the ref() property. craft\elements\db\ElementQuery
relatedTo() Sets the relatedTo() property. craft\elements\db\ElementQuery
rightJoin() Appends a RIGHT OUTER JOIN part to the query. yii\db\Query
scalar() Returns the query result as a scalar value. craft\db\Query
search() Sets the search() property. craft\elements\db\ElementQuery
select() Sets the SELECT part of the query. yii\db\Query
setCachedResult() Sets the resulting elements. craft\elements\db\ElementQuery
siblingOf() Sets the siblingOf() property. craft\elements\db\ElementQuery
site() Sets the siteId() property based on a given site(s)’s handle. craft\elements\db\ElementQuery
siteId() Sets the siteId() property. craft\elements\db\ElementQuery
slug() Sets the slug() property. craft\elements\db\ElementQuery
status() Sets the status() property. craft\elements\db\ElementQuery
structureId() Sets the structureId() property. craft\elements\db\ElementQuery
sum() Returns the sum of the specified column values. yii\db\Query
title() Sets the title() property. craft\elements\db\ElementQuery
toArray() Converts the model into an array. yii\base\ArrayableTrait
total() Returns the total elements that match the criteria. craft\elements\db\ElementQuery
trigger() Triggers an event. yii\base\Component
uid() Sets the uid() property. craft\elements\db\ElementQuery
union() Appends a SQL statement using UNION operator. yii\db\Query
uri() Sets the uri() property. craft\elements\db\ElementQuery
where() Sets the WHERE part of the query. yii\db\QueryTrait
with() Sets the with() property. craft\elements\db\ElementQuery
withStructure() Sets the withStructure() property. craft\elements\db\ElementQuery
Protected Methods
Method Description Defined By
afterPrepare() This method is called at the end of preparing an element query for the query builder. craft\elements\db\ElementQuery
beforePrepare() This method is called at the beginning of preparing an element query for the query builder. craft\elements\db\ElementQuery
cleanUpTableNames() Clean up table names and aliases Both aliases and names are enclosed into {{ and }}. yii\db\Query
customFields() Returns the fields that should take part in an upcoming elements query. craft\elements\db\ElementQuery
extractFieldsFor() Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id". yii\base\ArrayableTrait
extractRootFields() Extracts the root field names from nested fields. yii\base\ArrayableTrait
filterCondition() Removes empty operands from the given query condition. yii\db\QueryTrait
getUnaliasedColumnsFromSelect() yii\db\Query
getUniqueColumns() Returns unique column names excluding duplicates. yii\db\Query
isEmpty() Returns a value indicating whether the give value is "empty". yii\db\QueryTrait
joinElementTable() Joins in a table with an id column that has a foreign key pointing to craft_elements.id. craft\elements\db\ElementQuery
normalizeOrderBy() Normalizes format of ORDER BY data. craft\elements\db\ElementQuery
queryScalar() Queries a scalar value by setting select() first. craft\db\Query
resolveFields() Determines which fields can be returned by toArray(). yii\base\ArrayableTrait
setCommandCache() Sets $command cache, if this query has enabled caching. yii\db\Query
statusCondition() Returns the condition that should be applied to the element query for a given status. craft\elements\db\ElementQuery
Events
Event Type Description Defined By
EVENT_AFTER_POPULATE_ELEMENT craft\events\PopulateElementEvent The event that is triggered after an element is populated. craft\elements\db\ElementQuery
EVENT_AFTER_PREPARE \craft\elements\db\Event An event that is triggered at the end of preparing an element query for the query builder. craft\elements\db\ElementQuery
EVENT_BEFORE_PREPARE \craft\elements\db\Event An event that is triggered at the beginning of preparing an element query for the query builder. craft\elements\db\ElementQuery
EVENT_DEFINE_BEHAVIORS craft\events\DefineBehaviorsEvent The event that is triggered when defining the class behaviors craft\db\Query
EVENT_INIT yii\base\Event The event that is triggered after the query's init cycle craft\db\Query

Property Details

$ancestorDist public property #

The maximum number of levels that results may be separated from ancestorOf().

public integer, null $ancestorDist null

$ancestorOf public property #

The element (or its ID) that results must be an ancestor of.

public integer, craft\base\ElementInterface, null $ancestorOf null

$archived public property #

Whether to return only archived elements.

public boolean $archived false

$asArray public property #

Whether to return each element as an array. If false (default), an object of $elementType will be created to represent each element.

public boolean $asArray false

$contentTable public property #

The content table that will be joined by this query.

public string, null $contentTable '{{%content}}'

$customFields public property #

The fields that may be involved in this query.

public craft\base\FieldInterface[], null $customFields null

$dateCreated public property #

When the resulting elements must have been created.

public mixed $dateCreated null

$dateUpdated public property #

When the resulting elements must have been last updated.

public mixed $dateUpdated null

$defaultOrderBy protected property #

The default orderBy() value to use if orderBy() is empty but not null.

protected array $defaultOrderBy = ['elements.dateCreated' => SORT_DESC]

$descendantDist public property #

The maximum number of levels that results may be separated from descendantOf().

public integer, null $descendantDist null

$descendantOf public property #

The element (or its ID) that results must be a descendant of.

public integer, craft\base\ElementInterface, null $descendantOf null

$elementType public property #

The name of the craft\base\ElementInterface class.

public string, null $elementType null

$enabledForSite public property #

Whether the elements must be enabled for the chosen site.

public boolean $enabledForSite true

$fixedOrder public property #

Whether results should be returned in the order specified by id().

public boolean $fixedOrder false

$id public property #

The element ID(s). Prefix IDs with "not " to exclude them.

public integer, integer[], false, null $id null

$inReverse public property #

Whether the results should be queried in reverse.

public boolean $inReverse false

$level public property #

The element’s level within the structure

public mixed $level null

$nextSiblingOf public property #

The element (or its ID) that the result must be the next sibling of.

public integer, craft\base\ElementInterface, null $nextSiblingOf null

$orderBy public property #

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 yii\db\ExpressionInterface objects. If that is the case, the expressions will be converted into strings without any change.

public array $orderBy ''

$positionedAfter public property #

The element (or its ID) that the results must be positioned after.

public integer, craft\base\ElementInterface, null $positionedAfter null

$positionedBefore public property #

The element (or its ID) that the results must be positioned before.

public integer, craft\base\ElementInterface, null $positionedBefore null

$prevSiblingOf public property #

The element (or its ID) that the result must be the previous sibling of.

public integer, craft\base\ElementInterface, null $prevSiblingOf null

$query public property #

The query object created by prepare()

See also prepare().

public craft\db\Query, null $query null

$ref public property #

The reference code(s) used to identify the element(s). This property is set when accessing elements via their reference tags, e.g. {entry:section/slug}.

public string, string[], null $ref null

$relatedTo public property #

The element relation criteria.

public integer, array, craft\base\ElementInterface, null $relatedTo null

$search public property #

The search term to filter the resulting elements by.

public string, array, craft\search\SearchQuery, null $search null

$siblingOf public property #

The element (or its ID) that the results must be a sibling of.

public integer, craft\base\ElementInterface, null $siblingOf null

$siteId public property #

The site ID that the elements should be returned in.

public integer, null $siteId null

$slug public property #

The slug that resulting elements must have.

public string, string[], null $slug null

$status public property #

The status(es) that the resulting elements must have.

public string, string[], null $status = ['enabled']

$structureId public property #

The structure ID that should be used to join in the structureelements table.

public integer, false, null $structureId null

$subQuery public property #

The subselect’s query object created by prepare()

See also prepare().

public craft\db\Query, null $subQuery null

$title public property #

The title that resulting elements must have.

public string, string[], null $title null

$uid public property #

The element UID(s). Prefix UIDs with "not " to exclude them.

public string, string[], null $uid null

$uri public property #

The URI that the resulting element must have.

public string, string[], null $uri null

$with public property #

The eager-loading declaration

public string, array, null $with null

$withStructure public property #

Whether element structure data should automatically be left-joined into the query.

public boolean, null $withStructure null

Method Details

__call() public method #

Calls the named method which is not a class method.

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.

public mixed __call ( $name, $params )
$name string The method name
$params array Method parameters
return mixed The method return value
throws yii\base\UnknownMethodException when calling unknown method

__construct() public method #

Constructor

public void __construct ( \craft\elements\db\string $elementType, array $config = [] )
$elementType string The element type class associated with this query
$config array Configurations to be applied to the newly created query object

__get() public method #

Returns the value of a component property.

This method will check in the following order and act accordingly:

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $component->property;.

public mixed __get ( $name )
$name string The property name
return mixed The property value or the value of a behavior's property
throws yii\base\UnknownPropertyException if the property is not defined
throws yii\base\InvalidCallException if the property is write-only.

__isset() public method #

Checks if a property is set, i.e. defined and not null.

This method will check in the following order and act accordingly:

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property).

public boolean __isset ( $name )
$name string The property name or the event name
return boolean Whether the named property is set

__set() public method #

Sets the value of a component property.

This method will check in the following order and act accordingly:

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $component->property = $value;.

public void __set ( $name, $value )
$name string The property name or the event name
$value mixed The property value
throws yii\base\UnknownPropertyException if the property is not defined
throws yii\base\InvalidCallException if the property is read-only.

addOrderBy() public method #

Adds additional ORDER BY columns to the query.

public $this addOrderBy ( $columns )
$columns string, array, yii\db\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 yii\db\ExpressionInterface object can be passed to specify the ORDER BY part explicitly in plain SQL.
return $this The query object itself

afterPrepare() protected method #

This method is called at the end of preparing an element query for the query builder.

It is called at the beginning of prepare(), right after $query and $subQuery have been created.

See also:

protected boolean afterPrepare ( )
return boolean Whether the query should be prepared and returned to the query builder. If false, the query will be cancelled and no results will be returned.

all() public method #

Executes the query and returns all results as an array.

public array all ( $db null )
$db yii\db\Connection The database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.
return array The query results. If the query results in nothing, an empty array will be returned.

ancestorDist() public method #

Sets the ancestorDist() property.

public static ancestorDist ( \craft\elements\db\int $value null )
$value integer, null The property value
return static Self reference

ancestorOf() public method #

Sets the ancestorOf() property.

public static ancestorOf ( $value )
$value integer, craft\base\ElementInterface, null The property value
return static Self reference

archived() public method #

Sets the archived() property.

public static archived ( \craft\elements\db\bool $value true )
$value boolean The property value (defaults to true)
return static Self reference

asArray() public method #

Sets the asArray() property.

public static asArray ( \craft\elements\db\bool $value true )
$value boolean The property value (defaults to true)
return static Self reference

beforePrepare() protected method #

This method is called at the beginning of preparing an element query for the query builder.

The main Query object being prepared for the query builder is available via $query. The subselect’s Query object being prepared is available via $subQuery. The role of the subselect query is to apply conditions to the query and narrow the result set down to just the elements that should actually be returned. The role of the main query is to join in any tables that should be included in the results, and select all of the columns that should be included in the results.

See also:

protected boolean beforePrepare ( )
return boolean Whether the query should be prepared and returned to the query builder. If false, the query will be cancelled and no results will be returned.

behaviors() public method #

Returns a list of behaviors that this component should behave as.

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 \craft\elements\db\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).

public array behaviors ( )
return array The behavior configurations.

count() public method #

Returns the number of records.

public integer, string count ( $q '*', $db null )
$q string The COUNT expression. Defaults to '*'. Make sure you properly quote column names in the expression.
$db yii\db\Connection 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 integer, string 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.

criteriaAttributes() public method #

Returns the query's criteria attributes.

public string[] criteriaAttributes ( )

customFields() protected method #

Returns the fields that should take part in an upcoming elements query.

These fields will get their own criteria parameters in the craft\elements\db\ElementQueryInterface that gets passed in, their field types will each have an opportunity to help build the element query, and their columns in the content table will be selected by the query (for those that have one). If a field has its own column in the content table, but the column name is prefixed with something besides “field_”, make sure you set the columnPrefix attribute on the craft\base\Field, so craft\services\Elements::buildElementsQuery() knows which column to select.

protected craft\base\FieldInterface[] customFields ( )
return craft\base\FieldInterface[] The fields that should take part in the upcoming elements query

dateCreated() public method #

Sets the dateCreated() property.

public static dateCreated ( $value )
$value mixed The property value
return static Self reference

dateUpdated() public method #

Sets the dateUpdated() property.

public static dateUpdated ( $value )
$value mixed The property value
return static Self reference

descendantDist() public method #

Sets the descendantDist() property.

public static descendantDist ( \craft\elements\db\int $value null )
$value integer, null The property value
return static Self reference

descendantOf() public method #

Sets the descendantOf() property.

public static descendantOf ( $value )
$value integer, craft\base\ElementInterface, null The property value
return static Self reference

enabledForSite() public method #

Sets the enabledForSite() property.

public static enabledForSite ( \craft\elements\db\bool $value true )
$value boolean The property value (defaults to true)
return static Self reference

fields() public method #

Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.

A field is a named element in the returned array by toArray(). This method should return an array of field names or field definitions. If the former, the field name will be treated as an object property name whose value will be used as the field value. If the latter, the array key should be the field name while the array value should be the corresponding field definition which can be either an object property name or a PHP callable returning the corresponding field value. The signature of the callable should be:

function ($model, $field) {
    // return field value
}

For example, the following code declares four fields:

return [
    'email',
    'firstName' => 'first_name',
    'lastName' => 'last_name',
    'fullName' => function ($model) {
        return $model->first_name . ' ' . $model->last_name;
    },
];

See also toArray().

public array fields ( )
return array The list of field names or field definitions.

find() public method #

Deprecated in Craft 3.0. Use all() instead.

Returns all elements that match the criteria.

public craft\base\ElementInterface[] find ( array $attributes null )
$attributes array, null Any last-minute parameters that should be added.
return craft\base\ElementInterface[] The matched elements.

first() public method #

Deprecated in Craft 3.0. Use one() instead.

Returns the first element that matches the criteria.

public craft\base\ElementInterface, null first ( array $attributes null )
$attributes array, null

fixedOrder() public method #

Sets the fixedOrder() property.

public static fixedOrder ( \craft\elements\db\bool $value true )
$value boolean The property value (defaults to true)
return static Self reference

getCachedResult() public method #

Returns the resulting elements set by setCachedResult(), if the criteria params haven’t changed since then.

See also setCachedResult().

public craft\base\ElementInterface[], null getCachedResult ( )
return craft\base\ElementInterface[], null $elements The resulting elements, or null if setCachedResult() was never called or the criteria has changed

getCriteria() public method #

Returns an array of the current criteria attribute values.

public array getCriteria ( )

getIterator() public method #

Required by the IteratorAggregate interface.

public ArrayIterator getIterator ( )

id() public method #

Sets the id() property.

public static id ( $value )
$value integer, integer[], false, null The property value
return static Self reference

ids() public method #

Executes the query and returns the IDs of the resulting elements.

public integer[] ids ( $db null )
$db yii\db\Connection, null The database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.
return integer[] The resulting element IDs. An empty array is returned if no elements are found.

inReverse() public method #

Sets the inReverse() property.

public static inReverse ( \craft\elements\db\bool $value true )
$value boolean The property value
return static Self reference

joinElementTable() protected method #

Joins in a table with an id column that has a foreign key pointing to craft_elements.id.

protected void joinElementTable ( \craft\elements\db\string $table )
$table string The unprefixed table name. This will also be used as the table’s alias within the query.

last() public method #

Deprecated in Craft 3.0. Use nth() instead.

Returns the last element that matches the criteria.

public craft\base\ElementInterface, null last ( array $attributes null )
$attributes array, null

level() public method #

Sets the level() property.

public static level ( $value null )
$value mixed The property value
return static Self reference

locale() public method #

Deprecated in 3.0. Use site() or siteId() instead.

Sets the site() property.

public static locale ( \craft\elements\db\string $value )
$value string The property value
return static Self reference

localeEnabled() public method #

Deprecated in 3.0. Use enabledForSite() instead.

Sets the enabledForSite() property.

public static localeEnabled ( $value true )
$value mixed The property value (defaults to true)
return static Self reference

nextSiblingOf() public method #

Sets the nextSiblingOf() property.

public static nextSiblingOf ( $value )
$value integer, craft\base\ElementInterface, null The property value
return static Self reference

normalizeOrderBy() protected method #

Normalizes format of ORDER BY data.

protected array normalizeOrderBy ( $columns )
$columns array, string, yii\db\ExpressionInterface The columns value to normalize. See orderBy() and addOrderBy().

nth() public method #

Executes the query and returns a single row of result at a given offset.

public craft\base\ElementInterface, array, null nth ( \craft\elements\db\int $n, yii\db\Connection $db null )
$n integer The offset of the row to return. If offset() is set, $offset will be added to it.
$db yii\db\Connection, null The database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.
return craft\base\ElementInterface, array, null The element. Null is returned if the query results in nothing.

offsetExists() public method #

Required by the ArrayAccess interface.

public boolean offsetExists ( $name )
$name integer, string The offset to check

offsetGet() public method #

Required by the ArrayAccess interface.

public mixed offsetGet ( $name )
$name integer, string The offset to get
return mixed The element at the given offset

offsetSet() public method #

Required by the ArrayAccess interface.

public void offsetSet ( $name, $value )
$name string The offset to set
$value mixed The value
throws yii\base\NotSupportedException if $name is numeric

offsetUnset() public method #

Required by the ArrayAccess interface.

public void offsetUnset ( $name )
$name string The offset to unset
throws yii\base\NotSupportedException if $name is numeric

one() public method #

Executes the query and returns a single row of result.

public craft\base\ElementInterface, array, null one ( $db null )
$db yii\db\Connection The database connection used to generate the SQL statement. If this parameter is not given, the db application component will be used.
return craft\base\ElementInterface, array, null The first element. Null is returned if the query results in nothing.

order() public method #

Deprecated in Craft 3.0. Use orderBy() instead.

Sets the orderBy() property.

public static order ( \craft\elements\db\string $value )
$value string The property value
return static Self reference

populate() public method #

Converts the raw query results into the format as specified by this query.

This method is internally used to convert the data fetched from database into the format as required by this query.

public craft\base\ElementInterface[], array populate ( $rows )
$rows array The raw query result from database
return craft\base\ElementInterface[], array The resulting elements.

positionedAfter() public method #

Sets the positionedAfter() property.

public static positionedAfter ( $value )
$value integer, craft\base\ElementInterface, null The property value
return static Self reference

positionedBefore() public method #

Sets the positionedBefore() property.

public static positionedBefore ( $value )
$value integer, craft\base\ElementInterface, null The property value
return static Self reference

prepare() public method #

Prepares for building SQL.

This method is called by \craft\elements\db\QueryBuilder when it starts to build SQL from a query object. You may override this method to do some final preparation work when converting a query into a SQL statement.

public $this prepare ( $builder )
$builder yii\db\QueryBuilder
return $this A prepared query instance which will be used by \craft\elements\db\QueryBuilder to build the SQL
throws craft\db\QueryAbortedException if it can be determined that there won’t be any results

prevSiblingOf() public method #

Sets the prevSiblingOf() property.

public static prevSiblingOf ( $value )
$value integer, craft\base\ElementInterface, null The property value
return static Self reference

ref() public method #

Sets the ref() property.

public static ref ( $value )
$value string, string[], null The property value
return static Self reference

relatedTo() public method #

Sets the relatedTo() property.

public static relatedTo ( $value )
$value integer, array, craft\base\ElementInterface, null The property value
return static Self reference

search() public method #

Sets the search() property.

public static search ( $value )
$value string, array, craft\search\SearchQuery, null The property value
return static Self reference

setCachedResult() public method #

Sets the resulting elements.

If this is called, all() will return these elements rather than initiating a new SQL query, as long as none of the parameters have changed since setCachedResult() was called.

See also getCachedResult().

public void setCachedResult ( array $elements )
$elements craft\base\ElementInterface[] The resulting elements.

siblingOf() public method #

Sets the siblingOf() property.

public static siblingOf ( $value )
$value integer, craft\base\ElementInterface, null The property value
return static Self reference

site() public method #

Sets the siteId() property based on a given site(s)’s handle.

public static site ( $value )
$value string, craft\models\Site The property value
return static Self reference
throws yii\base\Exception if $value is an invalid site handle

siteId() public method #

Sets the siteId() property.

public static siteId ( \craft\elements\db\int $value null )
$value integer, null The property value
return static Self reference

slug() public method #

Sets the slug() property.

public static slug ( $value )
$value string, string[], null The property value
return static Self reference

status() public method #

Sets the status() property.

public static status ( $value )
$value string, string[], null The property value
return static Self reference

statusCondition() protected method #

Returns the condition that should be applied to the element query for a given status.

For example, if you support a status called “pending”, which maps back to a pending database column that will either be 0 or 1, this method could do this:

protected function statusCondition($status)
{
    switch ($status) {
        case 'pending':
            return ['mytable.pending' => 1];
        default:
            return parent::statusCondition($status);
    }
protected string, array, yii\db\ExpressionInterface, false, null statusCondition ( \craft\elements\db\string $status )
$status string The status
return string, array, yii\db\ExpressionInterface, false, null The status condition, or false if $status is an unsupported status

structureId() public method #

Sets the structureId() property.

public static structureId ( \craft\elements\db\int $value null )
$value integer, null The property value
return static Self reference

title() public method #

Sets the title() property.

public static title ( $value )
$value string, string[], null The property value
return static Self reference

total() public method #

Deprecated in Craft 3.0. Use count() instead.

Returns the total elements that match the criteria.

public integer total ( array $attributes null )
$attributes array, null

uid() public method #

Sets the uid() property.

public static uid ( $value )
$value string, string[], null The property value
return static Self reference

uri() public method #

Sets the uri() property.

public static uri ( $value )
$value string, string[], null The property value
return static Self reference

with() public method #

Sets the with() property.

public self with ( $value )
$value string, array, null The property value
return self The query object itself

withStructure() public method #

Sets the withStructure() property.

public static withStructure ( \craft\elements\db\bool $value true )
$value boolean The property value (defaults to true)
return static Self reference

Event Details

EVENT_AFTER_POPULATE_ELEMENT event of type craft\events\PopulateElementEvent #

The event that is triggered after an element is populated.

EVENT_AFTER_PREPARE event of type \craft\elements\db\Event #

An event that is triggered at the end of preparing an element query for the query builder.

EVENT_BEFORE_PREPARE event of type \craft\elements\db\Event #

An event that is triggered at the beginning of preparing an element query for the query builder.