Query ​
- Type
- Class
- Namespace
- craft\db
- Inherits
- craft\db\Query » yii\db\Query » yii\base\Component » yii\base\BaseObject
- Implements
- ArrayAccess, IteratorAggregate, yii\base\Configurable, yii\db\ExpressionInterface, yii\db\QueryInterface
- Uses traits
- craft\base\ClonefixTrait, yii\db\QueryTrait
- Extended by
- craft\elements\db\AddressQuery, craft\elements\db\AssetQuery, craft\elements\db\CategoryQuery, craft\elements\db\ElementQuery, craft\elements\db\EntryQuery, craft\elements\db\GlobalSetQuery, craft\elements\db\TagQuery, craft\elements\db\UserQuery, craft\test\mockclasses\elements\MockElementQuery
- Since
- 3.0.0
Class Query
Public Properties ​
Property | Description |
---|---|
behaviors | yii\base\Behavior – List of behaviors attached to this component. |
distinct | boolean – Whether to select distinct rows of data only. |
emulateExecution | boolean – Whether to emulate the actual query execution, returning empty or false results. |
from | array, null – The table(s) to be selected from. |
groupBy | array, null – How to group the query results. |
having | string, array, yii\db\ExpressionInterface, null – The condition to be applied in the GROUP BY clause. |
indexBy | string, callable, null – The name of the column by which the query results should be indexed by. |
iterator | ArrayIterator |
join | array, null – How to join with other tables. |
limit | integer, yii\db\ExpressionInterface, null – Maximum number of records to be returned. |
offset | integer, yii\db\ExpressionInterface, null – Zero-based offset from where the records are to be returned. |
orderBy | array, null – How to sort the query results. |
params | array, null – List of query parameter values indexed by parameter placeholders. |
queryCacheDependency | yii\caching\Dependency, null – The dependency to be associated with the cached query result for this query |
queryCacheDuration | integer, boolean, null – The default number of seconds that query results can remain valid in cache. |
rawSql | string |
select | array, null – The columns being selected. |
selectOption | string, null – Additional option that should be appended to the 'SELECT' keyword. |
tablesUsedInFrom | string[] – Table names indexed by aliases. |
union | array, null – This is used to construct the UNION clause(s) in a SQL statement. |
where | string, array, yii\db\ExpressionInterface, null – Query condition. |
withQueries | array, null – This is used to construct the WITH section in a SQL query. |
iterator
​
- Type
- ArrayIterator
- Default value
null
- Access
- Read-only
- Since
- 4.2.0
rawSql
​
- Type
- string
- Default value
null
- Access
- Read-only
Public Methods ​
Method | Description |
---|---|
__call() | Calls the named method which is not a class method. |
__clone() | This method is called after the object is created by cloning an existing one. |
__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 a component property to be 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. |
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. |
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. |
collect() | Executes the query and returns all results as a collection. |
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. |
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. |
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. |
filterHaving() | Sets the HAVING part of the query but ignores empty operands. |
filterWhere() | Sets the WHERE part of the query but ignores empty operands. |
from() | Sets the FROM part of the query. |
getBehavior() | Returns the named behavior object. |
getBehaviors() | Returns all behaviors attached to this component. |
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. |
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 for this component. |
having() | Sets the HAVING part of the query. |
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. |
leftJoin() | Appends a LEFT OUTER JOIN part to the query. |
limit() | Sets the LIMIT part of the query. |
max() | Returns the maximum of the specified column values. |
min() | Returns the minimum of the specified column values. |
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() | Sets the OFFSET part of the query. |
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. |
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. |
prepare() | Prepares for building SQL. |
rightJoin() | Appends a RIGHT OUTER JOIN part to the query. |
scalar() | Returns the query result as a scalar value. |
select() | Sets the SELECT part of the query. |
sum() | Returns the sum of the specified column values. |
trigger() | Triggers an event. |
union() | Appends a SQL statement using UNION operator. |
where() | Sets the WHERE part of the query. |
withQuery() | Prepends a SQL statement using WITH syntax. |
addGroupBy()
​
Adds additional group-by columns to the existing ones.
Arguments ​
$columns
(string, array, yii\db\ExpressionInterface) – Additional columns to be grouped by. Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression).
Note that if your group-by is an expression containing commas, you should always use an array to represent the group-by information. Otherwise, the method will not be able to correctly determine the group-by columns.
Since version 2.0.7, an \craft\db\Expression
object can be passed to specify the GROUP BY part explicitly in plain SQL. Since version 2.0.14, an craft\db\ExpressionInterface object can be passed as well.
Returns ​
$this – The query object itself
all()
​
Executes the query and returns all results as an array.
Arguments ​
$db
(yii\db\Connection, null) – The database connection used to generate the SQL statement. If this parameter is not given, thedb
application component will be used.
Returns ​
array – The query results. If the query results in nothing, an empty array will be returned.
andWhere()
​
Adds an additional WHERE condition to the existing one.
The new condition and the existing one will be joined using the AND
operator.
Arguments ​
$condition
(string, array, yii\db\ExpressionInterface) – The new WHERE condition. Please refer to where() on how to specify this parameter.$params
(array) – The parameters (name => value) to be bound to the query.
Returns ​
$this – The query object itself
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\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).
Returns ​
array – The behavior configurations.
collect()
​
- Since
- 4.0.0
Executes the query and returns all results as a collection.
Arguments ​
$db
(yii\db\Connection, null) – The database connection used to generate the SQL statement. If this parameter is not given, thedb
application component will be used.
Returns ​
\Illuminate\Support\Collection<\craft\db\TKey,\craft\db\TValue>
– A collection of the resulting elements.
column()
​
Executes the query and returns the first column of the result.
Arguments ​
$db
(yii\db\Connection, null) – The database connection used to generate the SQL statement. If this parameter is not given, thedb
application component will be used.
Returns ​
array – The first column of the query result. An empty array is returned if the query results in nothing.
exists()
​
Returns a value indicating whether the query result contains any row of data.
Arguments ​
$db
(yii\db\Connection, null) – The database connection used to generate the SQL statement. If this parameter is not given, thedb
application component will be used.
Returns ​
boolean – Whether the query result contains any row of data.
getIterator()
​
- Since
- 4.2.0
Required by the IteratorAggregate interface.
Returns ​
getRawSql()
​
Shortcut for createCommand()->getRawSql()
.
See also:
Arguments ​
$db
(yii\db\Connection, null) – The database connection used to generate the SQL statement. If this parameter is not given, thedb
application component will be used.
Returns ​
groupBy()
​
Sets the GROUP BY part of the query.
Arguments ​
$columns
(string, array, yii\db\ExpressionInterface, null) – The columns to be grouped by. Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression).
Note that if your group-by is an expression containing commas, you should always use an array to represent the group-by information. Otherwise, the method will not be able to correctly determine the group-by columns.
Since version 2.0.7, an craft\db\ExpressionInterface object can be passed to specify the GROUP BY part explicitly in plain SQL. Since version 2.0.14, an craft\db\ExpressionInterface object can be passed as well.
Returns ​
$this – The query object itself
init()
​
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
isJoined()
​
Returns whether a given table has been joined in this query.
Arguments ​
$table
(string)
Returns ​
nth()
​
Executes the query and returns a single row of result at a given offset.
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, thedb
application component will be used.
Returns ​
mixed
– The row (in terms of an array) of the query result. Null is returned if the query results in nothing.
offsetExists()
​
- Since
- 4.2.0
Required by the ArrayAccess interface.
Arguments ​
$offset
(mixed
)
Returns ​
offsetGet()
​
- Since
- 4.2.0
Required by the ArrayAccess interface.
Arguments ​
$offset
(mixed
)
Returns ​
mixed
Throws ​
offsetSet()
​
- Since
- 4.2.0
Required by the ArrayAccess interface.
Arguments ​
$offset
(mixed
)$value
(mixed
)
Throws ​
offsetUnset()
​
- Since
- 4.2.0
Required by the ArrayAccess interface.
Arguments ​
$offset
(mixed
)
Returns ​
void
Throws ​
one()
​
Executes the query and returns a single row of result.
Arguments ​
$db
(yii\db\Connection, null) – The database connection used to generate the SQL statement. If this parameter is not given, thedb
application component will be used.
Returns ​
\craft\db\TValue
, null – The first row (in terms of an array) of the query result. False is returned if the query results in nothing.
orWhere()
​
Adds an additional WHERE condition to the existing one.
The new condition and the existing one will be joined using the OR
operator.
Arguments ​
$condition
(string, array, yii\db\ExpressionInterface) – The new WHERE condition. Please refer to where() on how to specify this parameter.$params
(array) – The parameters (name => value) to be bound to the query.
Returns ​
$this – The query object itself
pairs()
​
Executes the query and returns the first two columns in the results as key/value pairs.
Arguments ​
$db
(yii\db\Connection, null) – The database connection used to execute the query. If this parameter is not given, thedb
application component will be used.
Returns ​
array – The query results. If the query results in nothing, an empty array will be returned.
Throws ​
- yii\base\Exception
if less than two columns were selected
scalar()
​
Returns the query result as a scalar value.
The value returned will be the first column in the first row of the query results.
Arguments ​
$db
(yii\db\Connection, null) – The database connection used to generate the SQL statement. If this parameter is not given, thedb
application component will be used.
Returns ​
string, integer, null, false – The value of the first column in the first row of the query result. False is returned if the query result is empty.
where()
​
Sets the WHERE part of the query.
The method requires a $condition
parameter, and optionally a $params
parameter specifying the values to be bound to the query.
The $condition
parameter should be either a string (e.g. 'id=1'
) or an array.
Arguments ​
$condition
(string, array, yii\db\ExpressionInterface) – The conditions that should be put in the WHERE part.$params
(array) – The parameters (name => value) to be bound to the query.
Returns ​
$this – The query object itself
Protected Methods ​
Method | Description |
---|---|
cleanUpTableNames() | Clean up table names and aliases Both aliases and names are enclosed into . |
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". |
normalizeOrderBy() | Normalizes format of ORDER BY data. |
normalizeSelect() | Normalizes the SELECT columns passed to select() or addSelect(). |
queryScalar() | Queries a scalar value by setting select() first. |
setCommandCache() | Sets $command cache, if this query has enabled caching. |
normalizeSelect()
​
Normalizes the SELECT columns passed to select() or addSelect().
Arguments ​
$columns
(string, array, yii\db\ExpressionInterface)
Returns ​
queryScalar()
​
Queries a scalar value by setting select() first.
Restores the value of select to make this query reusable.
Arguments ​
$selectExpression
(string, yii\db\ExpressionInterface)$db
(yii\db\Connection, null) – The database connection used to execute the query.
Returns ​
Throws ​
- Throwable
if can't create command
Events ​
EVENT_DEFINE_BEHAVIORS ​
The event that is triggered when defining the class behaviors
See also behaviors()
EVENT_INIT ​
- Type
- yii\base\Event
The event that is triggered after the query's init cycle
See also init()