ElementQuery

Type
Class
Namespace
craft\elements\db
Inherits
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
craft\base\ClonefixTrait, yii\base\ArrayableTrait, yii\db\QueryTrait
Extended by
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
Since
3.0

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

View source

Public Properties

PropertyDescription
$ancestorDistinteger, null – The maximum number of levels that results may be separated from ancestorOf().
$ancestorOfinteger, craft\base\ElementInterface, null – The element (or its ID) that results must be an ancestor of.
$archivedboolean – Whether to return only archived elements.
$asArrayboolean – Whether to return each element as an array.
$behaviorsyii\base\Behavior – List of behaviors attached to this component
$cachedResultcraft\base\ElementInterface[], null – $elements The resulting elements, or null if setCachedResult() was never called or the criteria has changed
$contentTablestring, null – The content table that will be joined by this query.
$criteriaarray
$customFieldscraft\base\FieldInterface[], null – The fields that may be involved in this query.
$dateCreatedmixed – When the resulting elements must have been created.
$dateUpdatedmixed – When the resulting elements must have been last updated.
$descendantDistinteger, null – The maximum number of levels that results may be separated from descendantOf().
$descendantOfinteger, craft\base\ElementInterface, null – The element (or its ID) that results must be a descendant of.
$distinctboolean – Whether to select distinct rows of data only.
$elementTypestring, null – The name of the craft\base\ElementInterface class.
$emulateExecutionboolean – Whether to emulate the actual query execution, returning empty or false results.
$enabledForSiteboolean – Whether the elements must be enabled for the chosen site.
$fixedOrderboolean – Whether results should be returned in the order specified by id().
$fromarray – The table(s) to be selected from.
$groupByarray – How to group the query results.
$hasDescendantsboolean, null – Whether the resulting elements must have descendants.
$havingstring, array, yii\db\ExpressionInterface – The condition to be applied in the GROUP BY clause.
$idinteger, integer[], false, null – The element ID(s).
$inReverseboolean – Whether the results should be queried in reverse.
$indexBystring, callable – The name of the column by which the query results should be indexed by.
$iteratorArrayIterator
$joinarray – How to join with other tables.
$leavesboolean – Whether the elements must be “leaves” in the structure.
$levelmixed – The element’s level within the structure
$limitinteger, yii\db\ExpressionInterface – Maximum number of records to be returned.
$nextSiblingOfinteger, craft\base\ElementInterface, null – The element (or its ID) that the result must be the next sibling of.
$offsetinteger, yii\db\ExpressionInterface – Zero-based offset from where the records are to be returned.
$orderByarray – How to sort the query results.
$paramsarray – List of query parameter values indexed by parameter placeholders.
$positionedAfterinteger, craft\base\ElementInterface, null – The element (or its ID) that the results must be positioned after.
$positionedBeforeinteger, craft\base\ElementInterface, null – The element (or its ID) that the results must be positioned before.
$prevSiblingOfinteger, craft\base\ElementInterface, null – The element (or its ID) that the result must be the previous sibling of.
$querycraft\db\Query, null – The query object created by prepare()
$queryCacheDependencyyii\caching\Dependency – The dependency to be associated with the cached query result for this query
$queryCacheDurationinteger, true – The default number of seconds that query results can remain valid in cache.
$rawSqlstring
$refstring, string[], null – The reference code(s) used to identify the element(s).
$relatedTointeger, array, craft\base\ElementInterface, null – The element relation criteria.
$searchstring, array, craft\search\SearchQuery, null – The search term to filter the resulting elements by.
$selectarray – The columns being selected.
$selectOptionstring – Additional option that should be appended to the 'SELECT' keyword.
$siblingOfinteger, craft\base\ElementInterface, null – The element (or its ID) that the results must be a sibling of.
$siteIdinteger, null – The site ID that the elements should be returned in.
$slugstring, string[], null – The slug that resulting elements must have.
$statusstring, string[], null – The status(es) that the resulting elements must have.
$structureIdinteger, false, null – The structure ID that should be used to join in the structureelements table.
$subQuerycraft\db\Query, null – The subselect’s query object created by prepare()
$tablesUsedInFromstring[] – Table names indexed by aliases
$titlestring, string[], null – The title that resulting elements must have.
$uidstring, string[], null – The element UID(s).
$unionarray – This is used to construct the UNION clause(s) in a SQL statement.
$uristring, string[], null – The URI that the resulting element must have.
$wherestring, array – Query condition.
$withstring, array, null – The eager-loading declaration.
$withStructureboolean, null – Whether element structure data should automatically be left-joined into the query.

$ancestorDist

Type
integer, null

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

View source

Signature

public integer, null $ancestorDist = null

$ancestorOf

Type
integer, craft\base\ElementInterface, null

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

View source

Signature

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

$archived

Type
boolean

Whether to return only archived elements.

View source

Signature

public boolean $archived = false

$asArray

Type
boolean

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

View source

Signature

public boolean $asArray = false

$cachedResult

Type
craft\base\ElementInterface[], null

$elements The resulting elements, or null if setCachedResult() was never called or the criteria has changed

View source

Signature

public craft\base\ElementInterface[], null getCachedResult ( )
public void setCachedResult ( array $elements )

$contentTable

Type
string, null

The content table that will be joined by this query.

View source

Signature

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

$criteria

Type
array
Access
Read-only

View source

Signature

public array getCriteria ( )

$customFields

Type
craft\base\FieldInterface[], null

The fields that may be involved in this query.

View source

Signature

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

$dateCreated

Type
mixed

When the resulting elements must have been created.

View source

Signature

public mixed $dateCreated = null

$dateUpdated

Type
mixed

When the resulting elements must have been last updated.

View source

Signature

public mixed $dateUpdated = null

$descendantDist

Type
integer, null

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

View source

Signature

public integer, null $descendantDist = null

$descendantOf

Type
integer, craft\base\ElementInterface, null

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

View source

Signature

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

$elementType

Signature

public string, null $elementType = null

$enabledForSite

Type
boolean

Whether the elements must be enabled for the chosen site.

View source

Signature

public boolean $enabledForSite = true

$fixedOrder

Type
boolean

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

View source

Signature

public boolean $fixedOrder = false

$hasDescendants

Type
boolean, null

Whether the resulting elements must have descendants.

View source

Signature

public boolean, null $hasDescendants = null

$id

Type
integer, integer[], false, null

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

View source

Signature

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

$inReverse

Type
boolean

Whether the results should be queried in reverse.

View source

Signature

public boolean $inReverse = false

$iterator

Type
ArrayIterator
Access
Read-only

View source

Signature

public ArrayIterator getIterator ( )

$leaves

Type
boolean

Whether the elements must be “leaves” in the structure.

View source

Signature

public boolean $leaves = false

$level

Type
mixed

The element’s level within the structure

View source

Signature

public mixed $level = null

$nextSiblingOf

Type
integer, craft\base\ElementInterface, null

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

View source

Signature

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

$orderBy

Type
array

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.

View source

Signature

public array $orderBy = ''

$positionedAfter

Type
integer, craft\base\ElementInterface, null

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

View source

Signature

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

$positionedBefore

Type
integer, craft\base\ElementInterface, null

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

View source

Signature

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

$prevSiblingOf

Type
integer, craft\base\ElementInterface, null

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

View source

Signature

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

$query

Type
craft\db\Query, null

The query object created by prepare()

See also prepare()

View source

Signature

public craft\db\Query, null $query = null

$ref

Type
string, string[], null

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

View source

Signature

public string, string[], null $ref = null

$relatedTo

Type
integer, array, craft\base\ElementInterface, null

The element relation criteria.

See Relations for supported syntax options.

View source

Signature

public integer, array, craft\base\ElementInterface, null $relatedTo = null
Type
string, array, craft\search\SearchQuery, null

The search term to filter the resulting elements by.

See Searching for supported syntax options.

View source

Signature

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

$siblingOf

Type
integer, craft\base\ElementInterface, null

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

View source

Signature

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

$siteId

Type
integer, null

The site ID that the elements should be returned in.

View source

Signature

public integer, null $siteId = null

$slug

Type
string, string[], null

The slug that resulting elements must have.

View source

Signature

public string, string[], null $slug = null

$status

Type
string, string[], null

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

View source

Signature

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

$structureId

Type
integer, false, null

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

View source

Signature

public integer, false, null $structureId = null

$subQuery

Type
craft\db\Query, null

The subselect’s query object created by prepare()

See also prepare()

View source

Signature

public craft\db\Query, null $subQuery = null

$title

Type
string, string[], null

The title that resulting elements must have.

View source

Signature

public string, string[], null $title = null

$uid

Type
string, string[], null

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

View source

Signature

public string, string[], null $uid = null

$uri

Type
string, string[], null

The URI that the resulting element must have.

View source

Signature

public string, string[], null $uri = null

$with

Type
string, array, null

The eager-loading declaration.

See Eager-Loading Elements for supported syntax options.

View source

Signature

public string, array, null $with = null

$withStructure

Type
boolean, null

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

View source

Signature

public boolean, null $withStructure = null

Protected Properties

PropertyDescription
$defaultOrderByarray – The default orderBy() value to use if orderBy() is empty but not null.

$defaultOrderBy

Type
array

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

View source

Signature

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

Public Methods

MethodDescription
__call()Calls the named method which is not a class method.
__clone()
__construct()Constructor
__get()Returns the value of a component property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets the value of a component property.
__toString()Returns the SQL representation of Query
__unset()Sets an object property to null.
addGroupBy()Adds additional group-by columns to the existing ones.
addOrderBy()Adds additional ORDER BY columns to the query.
addParams()Adds additional parameters to be bound to the query.
addSelect()Add more columns to the SELECT part of the query.
all()Executes the query and returns all results as an array.
ancestorDist()Narrows the query results to only {elements} that are up to a certain distance away from the {element} specified by ancestorOf().
ancestorOf()Narrows the query results to only {elements} that are ancestors of another {element}.
andFilterCompare()Adds a filtering condition for a specific column and allow the user to choose a filter operator.
andFilterHaving()Adds an additional HAVING condition to the existing one but ignores empty operands.
andFilterWhere()Adds an additional WHERE condition to the existing one but ignores empty operands.
andHaving()Adds an additional HAVING condition to the existing one.
andWhere()Adds an additional WHERE condition to the existing one.
andWith()Causes the query to return matching {elements} eager-loaded with related elements, in addition to the elements that were already specified by with().
anyStatus()Clears out the status() and enabledForSite() parameters.
archived()Sets the $archived property.
asArray()Causes the query to return matching {elements} as arrays of data, rather than [[{element-class}]] objects.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
average()Returns the average of the specified column values.
batch()Starts a batch query.
behaviors()Returns a list of behaviors that this component should behave as.
cache()Enables query cache for this Query.
canGetProperty()Returns a value indicating whether a property can be read.
canSetProperty()Returns a value indicating whether a property can be set.
className()Returns the fully qualified name of this class.
column()Executes the query and returns the first column of the result.
count()Returns the number of records.
create()Creates a new Query object and copies its property values from an existing one.
createCommand()Creates a DB command that can be used to execute this query.
criteriaAttributes()Returns the query's criteria attributes.
dateCreated()Narrows the query results based on the {elements}’ creation dates.
dateUpdated()Narrows the query results based on the {elements}’ last-updated dates.
descendantDist()Narrows the query results to only {elements} that are up to a certain distance away from the {element} specified by descendantOf().
descendantOf()Narrows the query results to only {elements} that are descendants of another {element}.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
distinct()Sets the value indicating whether to SELECT DISTINCT or not.
each()Starts a batch query and retrieves data row by row.
emulateExecution()Sets whether to emulate query execution, preventing any interaction with data storage.
enabledForSite()Narrows the query results based on whether the {elements} are enabled in the site they’re being queried in, per the site() parameter.
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.
exists()Returns a value indicating whether the query result contains any row of data.
extraFields()Returns the list of fields that can be expanded further and returned by toArray().
fields()Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.
filterHaving()Sets the HAVING part of the query but ignores empty operands.
filterWhere()Sets the WHERE part of the query but ignores empty operands.
find()Returns all elements that match the criteria.
first()Returns the first element that matches the criteria.
fixedOrder()Causes the query results to be returned in the order specified by id().
from()Sets the FROM part of the query.
getBehavior()Returns the named behavior object.
getBehaviors()Returns all behaviors attached to this component.
getCachedResult()Returns the resulting elements set by setCachedResult(), if the criteria params haven’t changed since then.
getCriteria()Returns an array of the current criteria attribute values.
getIterator()Required by the IteratorAggregate interface.
getRawSql()Shortcut for createCommand()->getRawSql().
getTablesUsedInFrom()Returns table names used in from() indexed by aliases.
groupBy()Sets the GROUP BY part of the query.
hasDescendants()Narrows the query results based on whether the {elements} have any descendants.
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.
hasMethod()Returns a value indicating whether a method is defined.
hasProperty()Returns a value indicating whether a property is defined.
having()Sets the HAVING part of the query.
id()Narrows the query results based on the {elements}’ IDs.
ids()Executes the query and returns the IDs of the resulting elements.
inReverse()Causes the query results to be returned in reverse order.
indexBy()Sets the indexBy() property.
init()Initializes the object.
innerJoin()Appends an INNER JOIN part to the query.
isJoined()Returns whether a given table has been joined in this query.
join()Appends a JOIN part to the query.
last()Returns the last element that matches the criteria.
leaves()Narrows the query results based on whether the {elements} are “leaves” ({elements} with no descendants).
leftJoin()Appends a LEFT OUTER JOIN part to the query.
level()Narrows the query results based on the {elements}’ level within the structure.
limit()Determines the number of {elements} that should be returned.
locale()Sets the \craft\elements\db\$site property.
localeEnabled()Sets the $enabledForSite property.
max()Returns the maximum of the specified column values.
min()Returns the minimum of the specified column values.
nextSiblingOf()Narrows the query results to only the {element} that comes immediately after another {element}.
noCache()Disables query cache for this Query.
nth()Executes the query and returns a single row of result at a given offset.
off()Detaches an existing event handler from this component.
offset()Determines how many {elements} should be skipped in the results.
offsetExists()Required by the ArrayAccess interface.
offsetGet()Required by the ArrayAccess interface.
offsetSet()Required by the ArrayAccess interface.
offsetUnset()Required by the ArrayAccess interface.
on()Attaches an event handler to an event.
one()Executes the query and returns a single row of result.
orFilterHaving()Adds an additional HAVING condition to the existing one but ignores empty operands.
orFilterWhere()Adds an additional WHERE condition to the existing one but ignores empty operands.
orHaving()Adds an additional HAVING condition to the existing one.
orWhere()Adds an additional WHERE condition to the existing one.
order()Sets the $orderBy property.
orderBy()Sets the ORDER BY part of the query.
pairs()Executes the query and returns the first two columns in the results as key/value pairs.
params()Sets the parameters to be bound to the query.
populate()Converts the raw query results into the format as specified by this query.
positionedAfter()Narrows the query results to only {elements} that are positioned after another {element}.
positionedBefore()Narrows the query results to only {elements} that are positioned before another {element}.
prepare()Prepares for building SQL.
prevSiblingOf()Narrows the query results to only the {element} that comes immediately before another {element}.
ref()Narrows the query results based on a reference string.
relatedTo()Narrows the query results to only {elements} that are related to certain other elements.
rightJoin()Appends a RIGHT OUTER JOIN part to the query.
scalar()Returns the query result as a scalar value.
search()Narrows the query results to only {elements} that match a search query.
select()Sets the SELECT part of the query.
setCachedResult()Sets the resulting elements.
siblingOf()Narrows the query results to only {elements} that are siblings of another {element}.
site()Determines which site the {elements} should be queried in.
siteId()Determines which site the {elements} should be queried in, per the site’s ID.
slug()Narrows the query results based on the {elements}’ slugs.
status()Narrows the query results based on the {elements}’ statuses.
structureId()Determines which structure data should be joined into the query.
sum()Returns the sum of the specified column values.
title()Narrows the query results based on the {elements}’ titles.
toArray()Converts the model into an array.
total()Returns the total elements that match the criteria.
trigger()Triggers an event.
uid()Narrows the query results based on the {elements}’ UIDs.
union()Appends a SQL statement using UNION operator.
uri()Narrows the query results based on the {elements}’ URIs.
where()Sets the WHERE part of the query.
with()Causes the query to return matching {elements} eager-loaded with related elements.
withStructure()Explicitly determines whether the query should join in the structure data.

__call()

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.

View source

Arguments

  • $name (string) – The method name
  • $params (array) – Method parameters

Returns

mixed – The method return value

Throws

Signature

public mixed __call ( $name, $params )

__construct()

Constructor

View source

Arguments

  • $elementType (string) – The element type class associated with this query
  • $config (array) – Configurations to be applied to the newly created query object

Signature

public void __construct ( \craft\elements\db\string $elementType, array $config = [] )

__get()

Returns the value of a component property.

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

View source

Arguments

  • $name (string) – The property name

Returns

mixed – The property value or the value of a behavior's property

Throws

Signature

public mixed __get ( $name )

__isset()

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

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

View source

Arguments

  • $name (string) – The property name or the event name

Returns

boolean – Whether the named property is set

Signature

public boolean __isset ( $name )

__set()

Sets the value of a component property.

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

View source

Arguments

  • $name (string) – The property name or the event name
  • $value (mixed) – The property value

Throws

Signature

public void __set ( $name, $value )

addOrderBy()

Adds additional ORDER BY columns to the query.

View source

Arguments

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

Returns

$this – The query object itself

Signature

public $this addOrderBy ( $columns )

all()

Executes the query and returns all results as an array.

View source

Arguments

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

Returns

array – The query results. If the query results in nothing, an empty array will be returned.

Signature

public array all ( $db = null )

ancestorDist()

Narrows the query results to only {elements} that are up to a certain distance away from the {element} specified by ancestorOf().

View source

Arguments

Returns

static – Self reference

Signature

public static ancestorDist ( \craft\elements\db\int $value = null )

Example

ancestorOf()

Narrows the query results to only {elements} that are ancestors of another {element}.

Possible values include:

ValueFetches {elements}…
1above the {element} with an ID of 1.
a [[{element-class}]] objectabove the {element} represented by the object.

TIP

This can be combined with ancestorDist() if you want to limit how far away the ancestor {elements} can be.

View source

Arguments

Returns

static – Self reference

Signature

public static ancestorOf ( $value )

Example

andWith()

Causes the query to return matching {elements} eager-loaded with related elements, in addition to the elements that were already specified by with().

.

View source

Arguments

Returns

self – The query object itself

Signature

public self andWith ( $value )

anyStatus()

Clears out the status() and enabledForSite() parameters.

View source

Returns

static – Self reference

Signature

public static anyStatus ( )

Example

archived()

Sets the $archived property.

View source

Arguments

  • $value (boolean) – The property value (defaults to true)

Returns

static – Self reference

Signature

public static archived ( \craft\elements\db\bool $value = true )

asArray()

Causes the query to return matching {elements} as arrays of data, rather than [[{element-class}]] objects.

View source

Arguments

  • $value (boolean) – The property value (defaults to true)

Returns

static – Self reference

Signature

public static asArray ( \craft\elements\db\bool $value = true )

Example

behaviors()

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

View source

Returns

array – The behavior configurations.

Signature

public array behaviors ( )

count()

Returns the number of records.

View source

Arguments

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

Returns

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.

Signature

public integer, string count ( $q = '*', $db = null )

criteriaAttributes()

Returns the query's criteria attributes.

View source

Returns

string[]

Signature

public string[] criteriaAttributes ( )

dateCreated()

Narrows the query results based on the {elements}’ creation dates.

Possible values include:

ValueFetches {elements}…
'>= 2018-04-01'that were created on or after 2018-04-01.
'< 2018-05-01'that were created before 2018-05-01
['and', '>= 2018-04-04', '< 2018-05-01']that were created between 2018-04-01 and 2018-05-01.

View source

Arguments

  • $value (mixed) – The property value

Returns

static – Self reference

Signature

public static dateCreated ( $value )

Example

dateUpdated()

Narrows the query results based on the {elements}’ last-updated dates.

Possible values include:

ValueFetches {elements}…
'>= 2018-04-01'that were updated on or after 2018-04-01.
'< 2018-05-01'that were updated before 2018-05-01
['and', '>= 2018-04-04', '< 2018-05-01']that were updated between 2018-04-01 and 2018-05-01.

View source

Arguments

  • $value (mixed) – The property value

Returns

static – Self reference

Signature

public static dateUpdated ( $value )

Example

descendantDist()

Narrows the query results to only {elements} that are up to a certain distance away from the {element} specified by descendantOf().

View source

Arguments

Returns

static – Self reference

Signature

public static descendantDist ( \craft\elements\db\int $value = null )

Example

descendantOf()

Narrows the query results to only {elements} that are descendants of another {element}.

Possible values include:

ValueFetches {elements}…
1below the {element} with an ID of 1.
a [[{element-class}]] objectbelow the {element} represented by the object.

TIP

This can be combined with descendantDist() if you want to limit how far away the descendant {elements} can be.

View source

Arguments

Returns

static – Self reference

Signature

public static descendantOf ( $value )

Example

enabledForSite()

Narrows the query results based on whether the {elements} are enabled in the site they’re being queried in, per the site() parameter.

Possible values include:

ValueFetches {elements}…
true(default)that are enabled in the site.
falsewhether they are enabled or not in the site.

View source

Arguments

  • $value (boolean) – The property value (defaults to true)

Returns

static – Self reference

Signature

public static enabledForSite ( \craft\elements\db\bool $value = true )

Example

fields()

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:

  • email: the field name is the same as the property name email;
  • firstName and lastName: the field names are firstName and lastName, and their values are obtained from the first_name and last_name properties;
  • fullName: the field name is fullName. Its value is obtained by concatenating first_name and last_name.
return [
    'email',
    'firstName' => 'first_name',
    'lastName' => 'last_name',
    'fullName' => function ($model) {
        return $model->first_name . ' ' . $model->last_name;
    },
];

See also toArray()View source

Returns

array – The list of field names or field definitions.

Signature

public array fields ( )

find()

DEPRECATED

Deprecated in Craft 3.0. Use all() instead.

Returns all elements that match the criteria.

View source

Arguments

  • $attributes (array, null) – Any last-minute parameters that should be added.

Returns

craft\base\ElementInterface[] – The matched elements.

Signature

public craft\base\ElementInterface[] find ( array $attributes = null )

first()

DEPRECATED

Deprecated in Craft 3.0. Use one() instead.

Returns the first element that matches the criteria.

View source

Arguments

Returns

craft\base\ElementInterface, null

Signature

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

fixedOrder()

Causes the query results to be returned in the order specified by id().

View source

Arguments

  • $value (boolean) – The property value (defaults to true)

Returns

static – Self reference

Signature

public static fixedOrder ( \craft\elements\db\bool $value = true )

Example

getCachedResult()

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

See also setCachedResult()View source

Returns

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

Signature

public craft\base\ElementInterface[], null getCachedResult ( )

getCriteria()

Returns an array of the current criteria attribute values.

View source

Returns

array

Signature

public array getCriteria ( )

getIterator()

Required by the IteratorAggregate interface.

View source

Returns

ArrayIterator

Signature

public ArrayIterator getIterator ( )

hasDescendants()

Narrows the query results based on whether the {elements} have any descendants.

(This has the opposite effect of calling leaves().)

View source

Arguments

  • $value (boolean) – The property value

Returns

static – Self reference

Signature

public static hasDescendants ( \craft\elements\db\bool $value = true )

Example

id()

Narrows the query results based on the {elements}’ IDs.

Possible values include:

ValueFetches {elements}…
1with an ID of 1.
'not 1'not with an ID of 1.
[1, 2]with an ID of 1 or 2.
['not', 1, 2]not with an ID of 1 or 2.

TIP

This can be combined with fixedOrder() if you want the results to be returned in a specific order.

View source

Arguments

Returns

static – Self reference

Signature

public static id ( $value )

Example

ids()

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

View source

Arguments

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

Returns

integer[] – The resulting element IDs. An empty array is returned if no elements are found.

Signature

public integer[] ids ( $db = null )

inReverse()

Causes the query results to be returned in reverse order.

View source

Arguments

  • $value (boolean) – The property value

Returns

static – Self reference

Signature

public static inReverse ( \craft\elements\db\bool $value = true )

Example

last()

DEPRECATED

Deprecated in Craft 3.0. Use nth() instead.

Returns the last element that matches the criteria.

View source

Arguments

Returns

craft\base\ElementInterface, null

Signature

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

leaves()

Narrows the query results based on whether the {elements} are “leaves” ({elements} with no descendants).

(This has the opposite effect of calling hasDescendants().)

View source

Arguments

  • $value (boolean) – The property value

Returns

static – Self reference

Signature

public static leaves ( \craft\elements\db\bool $value = true )

Example

level()

Narrows the query results based on the {elements}’ level within the structure.

Possible values include:

ValueFetches {elements}…
1with a level of 1.
'not 1'not with a level of 1.
'>= 3'with a level greater than or equal to 3.
[1, 2]with a level of 1 or 2
['not', 1, 2]not with level of 1 or 2.

View source

Arguments

  • $value (mixed) – The property value

Returns

static – Self reference

Signature

public static level ( $value = null )

Example

locale()

DEPRECATED

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

Sets the \craft\elements\db\$site property.

View source

Arguments

  • $value (string) – The property value

Returns

static – Self reference

Signature

public static locale ( \craft\elements\db\string $value )

localeEnabled()

DEPRECATED

Deprecated in 3.0. Use enabledForSite() instead.

Sets the $enabledForSite property.

View source

Arguments

  • $value (mixed) – The property value (defaults to true)

Returns

static – Self reference

Signature

public static localeEnabled ( $value = true )

nextSiblingOf()

Narrows the query results to only the {element} that comes immediately after another {element}.

Possible values include:

ValueFetches the {element}…
1after the {element} with an ID of 1.
a [[{element-class}]] objectafter the {element} represented by the object.

View source

Arguments

Returns

static – Self reference

Signature

public static nextSiblingOf ( $value )

Example

nth()

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

View source

Arguments

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

Returns

craft\base\ElementInterface, array, null – The element. Null is returned if the query results in nothing.

Signature

public craft\base\ElementInterface, array, null nth ( \craft\elements\db\int $n, yii\db\Connection $db = null )

offsetExists()

Required by the ArrayAccess interface.

View source

Arguments

Returns

boolean

Signature

public boolean offsetExists ( $name )

offsetGet()

Required by the ArrayAccess interface.

View source

Arguments

Returns

mixed – The element at the given offset

Signature

public mixed offsetGet ( $name )

offsetSet()

Required by the ArrayAccess interface.

View source

Arguments

  • $name (string) – The offset to set
  • $value (mixed) – The value

Throws

Signature

public void offsetSet ( $name, $value )

offsetUnset()

Required by the ArrayAccess interface.

View source

Arguments

  • $name (string) – The offset to unset

Throws

Signature

public void offsetUnset ( $name )

one()

Executes the query and returns a single row of result.

View source

Arguments

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

Returns

craft\base\ElementInterface, array, null – The first element. Null is returned if the query results in nothing.

Signature

public craft\base\ElementInterface, array, null one ( $db = null )

order()

DEPRECATED

Deprecated in Craft 3.0. Use orderBy() instead.

Sets the $orderBy property.

View source

Arguments

  • $value (string) – The property value

Returns

static – Self reference

Signature

public static order ( \craft\elements\db\string $value )

orderBy()

Sets the ORDER BY part of the query.

View source

Arguments

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

Returns

$this – The query object itself

Signature

public $this orderBy ( $columns )

populate()

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.

View source

Arguments

  • $rows (array) – The raw query result from database

Returns

craft\base\ElementInterface[], array – The resulting elements.

Signature

public craft\base\ElementInterface[], array populate ( $rows )

positionedAfter()

Narrows the query results to only {elements} that are positioned after another {element}.

Possible values include:

ValueFetches {elements}…
1after the {element} with an ID of 1.
a [[{element-class}]] objectafter the {element} represented by the object.

View source

Arguments

Returns

static – Self reference

Signature

public static positionedAfter ( $value )

Example

positionedBefore()

Narrows the query results to only {elements} that are positioned before another {element}.

Possible values include:

ValueFetches {elements}…
1before the {element} with an ID of 1.
a [[{element-class}]] objectbefore the {element} represented by the object.

View source

Arguments

Returns

static – Self reference

Signature

public static positionedBefore ( $value )

Example

prepare()

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.

View source

Arguments

Returns

$this – A prepared query instance which will be used by \craft\elements\db\QueryBuilder to build the SQL

Throws

Signature

public $this prepare ( $builder )

prevSiblingOf()

Narrows the query results to only the {element} that comes immediately before another {element}.

Possible values include:

ValueFetches the {element}…
1before the {element} with an ID of 1.
a [[{element-class}]] objectbefore the {element} represented by the object.

View source

Arguments

Returns

static – Self reference

Signature

public static prevSiblingOf ( $value )

Example

ref()

Narrows the query results based on a reference string.

View source

Arguments

Returns

static – Self reference

Signature

public static ref ( $value )

relatedTo()

Narrows the query results to only {elements} that are related to certain other elements.

See Relations for a full explanation of how to work with this parameter.

View source

Arguments

Returns

static – Self reference

Signature

public static relatedTo ( $value )

Example

Narrows the query results to only {elements} that match a search query.

See Searching for a full explanation of how to work with this parameter.

View source

Arguments

Returns

static – Self reference

Signature

public static search ( $value )

Example

setCachedResult()

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()View source

Arguments

Signature

public void setCachedResult ( array $elements )

siblingOf()

Narrows the query results to only {elements} that are siblings of another {element}.

Possible values include:

ValueFetches {elements}…
1beside the {element} with an ID of 1.
a [[{element-class}]] objectbeside the {element} represented by the object.

View source

Arguments

Returns

static – Self reference

Signature

public static siblingOf ( $value )

Example

site()

Determines which site the {elements} should be queried in.

The current site will be used by default.

Possible values include:

ValueFetches {elements}…
'foo'from the site with a handle of foo.
a craft\models\Site objectfrom the site represented by the object.

View source

Arguments

Returns

static – Self reference

Throws

Signature

public static site ( $value )

Example

siteId()

Determines which site the {elements} should be queried in, per the site’s ID.

The current site will be used by default.

View source

Arguments

Returns

static – Self reference

Signature

public static siteId ( \craft\elements\db\int $value = null )

Example

slug()

Narrows the query results based on the {elements}’ slugs.

Possible values include:

ValueFetches {elements}…
'foo'with a slug of foo.
'foo*'with a slug that begins with foo.
'*foo'with a slug that ends with foo.
'*foo*'with a slug that contains foo.
'not *foo*'with a slug that doesn’t contain foo.
['*foo*', '*bar*'with a slug that contains foo or bar.
['not', '*foo*', '*bar*']with a slug that doesn’t contain foo or bar.

View source

Arguments

Returns

static – Self reference

Signature

public static slug ( $value )

Example

status()

Narrows the query results based on the {elements}’ statuses.

Possible values include:

ValueFetches {elements}…
'enabled'(default)that are enabled.
'disabled'that are disabled.

View source

Arguments

Returns

static – Self reference

Signature

public static status ( $value )

Example

structureId()

Determines which structure data should be joined into the query.

View source

Arguments

Returns

static – Self reference

Signature

public static structureId ( \craft\elements\db\int $value = null )

title()

Narrows the query results based on the {elements}’ titles.

Possible values include:

ValueFetches {elements}…
'Foo'with a title of Foo.
'Foo*'with a title that begins with Foo.
'*Foo'with a title that ends with Foo.
'*Foo*'with a title that contains Foo.
'not *Foo*'with a title that doesn’t contain Foo.
['*Foo*', '*Bar*'with a title that contains Foo or Bar.
['not', '*Foo*', '*Bar*']with a title that doesn’t contain Foo or Bar.

View source

Arguments

Returns

static – Self reference

Signature

public static title ( $value )

Example

total()

DEPRECATED

Deprecated in Craft 3.0. Use count() instead.

Returns the total elements that match the criteria.

View source

Arguments

Returns

integer

Signature

public integer total ( array $attributes = null )

uid()

Narrows the query results based on the {elements}’ UIDs.

View source

Arguments

Returns

static – Self reference

Signature

public static uid ( $value )

Example

uri()

Narrows the query results based on the {elements}’ URIs.

Possible values include:

ValueFetches {elements}…
'foo'with a URI of foo.
'foo*'with a URI that begins with foo.
'*foo'with a URI that ends with foo.
'*foo*'with a URI that contains foo.
'not *foo*'with a URI that doesn’t contain foo.
['*foo*', '*bar*'with a URI that contains foo or bar.
['not', '*foo*', '*bar*']with a URI that doesn’t contain foo or bar.

View source

Arguments

Returns

static – Self reference

Signature

public static uri ( $value )

Example

with()

Causes the query to return matching {elements} eager-loaded with related elements.

See Eager-Loading Elements for a full explanation of how to work with this parameter.

View source

Arguments

Returns

self – The query object itself

Signature

public self with ( $value )

Example

withStructure()

Explicitly determines whether the query should join in the structure data.

View source

Arguments

  • $value (boolean) – The property value (defaults to true)

Returns

static – Self reference

Signature

public static withStructure ( \craft\elements\db\bool $value = true )

Protected Methods

MethodDescription
afterPrepare()This method is called at the end of preparing an element query for the query builder.
beforePrepare()This method is called at the beginning of preparing an element query for the query builder.
cleanUpTableNames()Clean up table names and aliases Both aliases and names are enclosed into {{ and }}.
customFields()Returns the fields that should take part in an upcoming elements query.
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".
extractRootFields()Extracts the root field names from nested fields.
filterCondition()Removes empty operands from the given query condition.
getUnaliasedColumnsFromSelect()
getUniqueColumns()Returns unique column names excluding duplicates.
isEmpty()Returns a value indicating whether the give value is "empty".
joinElementTable()Joins in a table with an id column that has a foreign key pointing to craft_elements.id.
normalizeOrderBy()Normalizes format of ORDER BY data.
queryScalar()Queries a scalar value by setting select() first.
resolveFields()Determines which fields can be returned by toArray().
setCommandCache()Sets $command cache, if this query has enabled caching.
statusCondition()Returns the condition that should be applied to the element query for a given status.

afterPrepare()

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:

View source

Returns

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.

Signature

protected boolean afterPrepare ( )

beforePrepare()

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:

View source

Returns

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.

Signature

protected boolean beforePrepare ( )

customFields()

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.

View source

Returns

craft\base\FieldInterface[] – The fields that should take part in the upcoming elements query

Signature

protected craft\base\FieldInterface[] customFields ( )

joinElementTable()

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

View source

Arguments

  • $table (string) – The unprefixed table name. This will also be used as the table’s alias within the query.

Signature

protected void joinElementTable ( \craft\elements\db\string $table )

normalizeOrderBy()

Normalizes format of ORDER BY data.

View source

Arguments

Returns

array

Signature

protected array normalizeOrderBy ( $columns )

statusCondition()

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);
    }

View source

Arguments

  • $status (string) – The status

Returns

string, array, yii\db\ExpressionInterface, false, null – The status condition, or false if $status is an unsupported status

Signature

protected string, array, yii\db\ExpressionInterface, false, null statusCondition ( \craft\elements\db\string $status )

Events

EVENT_AFTER_POPULATE_ELEMENT

Type
craft\events\PopulateElementEvent

The event that is triggered after an element is populated.

EVENT_AFTER_PREPARE

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

Type
\craft\elements\db\Event

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