Skip to content
PHP Ecosystem
Explore

QueryBuilder

API reference › yii › db › QueryBuilder

classyii\db\QueryBuilder
Extendsyii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/db/QueryBuilder.php
5 subclasses

QueryBuilder builds a SELECT SQL statement based on the specification given as a Query object.

SQL statements are created from Query objects using the build()-method.

QueryBuilder is also used by Command to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE.

For more details and usage information on QueryBuilder, see the guide article on query builders.

PropertyTypeDescriptionDefined by
$dbConnectionThe database connection. Default: null.QueryBuilder
$separatorstringThe separator between different fragments of a SQL statement. Default: ' '.QueryBuilder
$typeMaparrayThe abstract column types mapped to physical column types. Default: [].QueryBuilder
$conditionClasses protectedarrayMap of condition aliases to condition classes. Default: []. Available since 2.0.14.QueryBuilder
$expressionBuilders protectedstring[]|ExpressionBuilderInterface[]Maps expression class to expression builder class. Default: []. Available since 2.0.14.QueryBuilder
MethodDescriptionDefined by
__construct()Constructor.QueryBuilder
__call()Calls the named method which is not a class method.yii\base\BaseObject
__get()Returns the value of an object property.yii\base\BaseObject
__isset()Checks if a property is set, i.e. defined and not null.yii\base\BaseObject
__set()Sets value of an object property.yii\base\BaseObject
__unset()Sets an object property to null.yii\base\BaseObject
addCheck()Creates a SQL command for adding a check constraint to an existing table.QueryBuilder
addColumn()Builds a SQL statement for adding a new DB column.QueryBuilder
addCommentOnColumn()Builds a SQL command for adding comment to column.QueryBuilder
addCommentOnTable()Builds a SQL command for adding comment to table.QueryBuilder
addDefaultValue()Creates a SQL command for adding a default value constraint to an existing table.QueryBuilder
addForeignKey()Builds a SQL statement for adding a foreign key constraint to an existing table.QueryBuilder
addPrimaryKey()Builds a SQL statement for adding a primary key constraint to an existing table.QueryBuilder
addUnique()Creates a SQL command for adding an unique constraint to an existing table.QueryBuilder
alterColumn()Builds a SQL statement for changing the definition of a column.QueryBuilder
batchInsert()Generates a batch INSERT SQL statement.QueryBuilder
bindParam()Helper method to add $value to $params array using PARAM_PREFIX.QueryBuilder
build()Generates a SELECT SQL statement from a Query object.QueryBuilder
buildColumns()Processes columns and properly quotes them if necessary.QueryBuilder
buildCondition()Parses the condition specification and generates the corresponding SQL expression.QueryBuilder
buildExpression()Builds given $expressionQueryBuilder
buildFrom()QueryBuilder
buildGroupBy()QueryBuilder
buildHaving()QueryBuilder
buildJoin()QueryBuilder
buildLimit()QueryBuilder
buildOrderBy()QueryBuilder
buildOrderByAndLimit()Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.QueryBuilder
buildSelect()QueryBuilder
buildUnion()QueryBuilder
buildUnionOrderByAndLimit()Builds the global ORDER BY and LIMIT/OFFSET clauses for a UNION query.QueryBuilder
buildWhere()QueryBuilder
buildWithQueries()QueryBuilder
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
checkIntegrity()Builds a SQL statement for enabling or disabling integrity check.QueryBuilder
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
createConditionFromArray()Transforms $condition defined in array format (as described in Query::where() to instance of ConditionInterface according to $conditionClasses map.QueryBuilder
createIndex()Builds a SQL statement for creating a new index.QueryBuilder
createTable()Builds a SQL statement for creating a new DB table.QueryBuilder
createView()Creates a SQL View.QueryBuilder
delete()Creates a DELETE SQL statement.QueryBuilder
dropCheck()Creates a SQL command for dropping a check constraint.QueryBuilder
dropColumn()Builds a SQL statement for dropping a DB column.QueryBuilder
dropCommentFromColumn()Builds a SQL command for adding comment to column.QueryBuilder
dropCommentFromTable()Builds a SQL command for adding comment to table.QueryBuilder
dropDefaultValue()Creates a SQL command for dropping a default value constraint.QueryBuilder
dropForeignKey()Builds a SQL statement for dropping a foreign key constraint.QueryBuilder
dropIndex()Builds a SQL statement for dropping an index.QueryBuilder
dropPrimaryKey()Builds a SQL statement for removing a primary key constraint to an existing table.QueryBuilder
dropTable()Builds a SQL statement for dropping a DB table.QueryBuilder
dropUnique()Creates a SQL command for dropping an unique constraint.QueryBuilder
dropView()Drops a SQL View.QueryBuilder
executeResetSequence()Execute a SQL statement for resetting the sequence value of a table’s primary key.QueryBuilder
getColumnType()Converts an abstract column type into a physical column type.QueryBuilder
getExpressionBuilder()Gets object of ExpressionBuilderInterface that is suitable for $expression.QueryBuilder
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
init()Initializes the object.QueryBuilder
insert()Creates an INSERT SQL statement.QueryBuilder
renameColumn()Builds a SQL statement for renaming a column.QueryBuilder
renameTable()Builds a SQL statement for renaming a DB table.QueryBuilder
resetSequence()Creates a SQL statement for resetting the sequence value of a table’s primary key.QueryBuilder
selectExists()Creates a SELECT EXISTS() SQL statement.QueryBuilder
setConditionClasses()Setter for $conditionClasses property.QueryBuilder
setExpressionBuilders()Setter for $expressionBuilders property.QueryBuilder
truncateTable()Builds a SQL statement for truncating a DB table.QueryBuilder
update()Creates an UPDATE SQL statement.QueryBuilder
upsert()Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique constraints), or update them if they do.QueryBuilder
concatUnionSql() protectedConcatenates the first SELECT statement with the UNION clauses built by buildUnion().QueryBuilder
defaultConditionClasses() protectedContains array of default condition classes. Extend this method, if you want to change default condition classes for the query builder. See $conditionClasses docs for details.QueryBuilder
defaultExpressionBuilders() protectedContains array of default expression builders. Extend this method and override it, if you want to change default expression builders for this query builder. See $expressionBuilders docs for details.QueryBuilder
extractAlias() protectedExtracts table alias if there is one or returns falseQueryBuilder
hasLimit() protectedChecks to see if the given limit is effective.QueryBuilder
hasOffset() protectedChecks to see if the given offset is effective.QueryBuilder
prepareInsertSelectSubQuery() protectedPrepare select-subquery and field names for INSERT INTO … SELECT SQL statement.QueryBuilder
prepareInsertValues() protectedPrepares a VALUES part for an INSERT SQL statement.QueryBuilder
prepareSelectQuery() protectedPerforms driver-specific preparation after Query::prepare().QueryBuilder
prepareUpdateSets() protectedPrepares a SET parts for an UPDATE SQL statement.QueryBuilder
prepareUpsertColumns() protectedQueryBuilder
prepareUpsertSets() protectedPrepares the SET assignments for the update branch of an upsert statement.QueryBuilder
ConstantValueDescriptionDefined by
PARAM_PREFIX':qp'The prefix for automatically generated query binding parameters.QueryBuilder
public string $separator = ' '

The separator between different fragments of a SQL statement.

Defaults to an empty space. This is mainly used by build() when generating a SQL statement.

public array $typeMap = []

The abstract column types mapped to physical column types.

This is mainly used to support creating/modifying tables using DB-independent data type specifications. Child classes should override this property to declare supported type mappings.

protected array $conditionClasses = []

Map of condition aliases to condition classes.

For example:

return [
'LIKE' => yii\db\condition\LikeCondition::class,
];

This property is used by createConditionFromArray() method. See default condition classes list in defaultConditionClasses() method.

In case you want to add custom conditions support, use the setConditionClasses() method.

Since

2.0.14

protected string[]|yii\db\ExpressionBuilderInterface[] $expressionBuilders = []

Maps expression class to expression builder class.

For example:

[
yii\db\Expression::class => yii\db\ExpressionBuilder::class
]

This property is mainly used by buildExpression() to build SQL expressions form expression objects. See default values in defaultExpressionBuilders() method.

To override existing builders or add custom, use setExpressionBuilder() method. New items will be added to the end of this array.

To find a builder, buildExpression() will check the expression class for its exact presence in this map. In case it is NOT present, the array will be iterated in reverse direction, checking whether the expression extends the class, defined in this map.

Since

2.0.14

public function __construct(yii\db\Connection $connection, array $config = [])

Constructor.

Parameters

ParameterTypeDescription
$connectionConnectionThe database connection.
$configarrayName-value pairs that will be used to initialize the object properties
public function addCheck(string $name, string $table, string $expression): string

Creates a SQL command for adding a check constraint to an existing table.

Parameters

ParameterTypeDescription
$namestringThe name of the check constraint. The name will be properly quoted by the method.
$tablestringThe table that the check constraint will be added to. The name will be properly quoted by the method.
$expressionstringThe SQL of the CHECK constraint.

Returns

string: The SQL statement for adding a check constraint to an existing table.

Since

2.0.13

public function addColumn(string $table, string $column, string $type): string

Builds a SQL statement for adding a new DB column.

Parameters

ParameterTypeDescription
$tablestringThe table that the new column will be added to. The table name will be properly quoted by the method.
$columnstringThe name of the new column. The name will be properly quoted by the method.
$typestringThe column type. The getColumnType() method will be invoked to convert abstract column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. For example, ‘string’ will be turned into ‘varchar(255)’, while ‘string not null’ will become ‘varchar(255) not null’.

Returns

string: The SQL statement for adding a new column.

public function addCommentOnColumn(string $table, string $column, string $comment): string

Builds a SQL command for adding comment to column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be commented. The table name will be properly quoted by the method.
$columnstringThe name of the column to be commented. The column name will be properly quoted by the method.
$commentstringThe text of the comment to be added. The comment will be properly quoted by the method.

Returns

string: The SQL statement for adding comment on column

Since

2.0.8

public function addCommentOnTable(string $table, string $comment): string

Builds a SQL command for adding comment to table.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be commented. The table name will be properly quoted by the method.
$commentstringThe text of the comment to be added. The comment will be properly quoted by the method.

Returns

string: The SQL statement for adding comment on table

Since

2.0.8

public function addDefaultValue(string $name, string $table, string $column, mixed $value): string

Creates a SQL command for adding a default value constraint to an existing table.

Parameters

ParameterTypeDescription
$namestringThe name of the default value constraint. The name will be properly quoted by the method.
$tablestringThe table that the default value constraint will be added to. The name will be properly quoted by the method.
$columnstringThe name of the column to that the constraint will be added on. The name will be properly quoted by the method.
$valuemixedDefault value.

Returns

string: The SQL statement for adding a default value constraint to an existing table.

Throws

Since

2.0.13

public function addForeignKey(string $name, string $table, string|array $columns, string $refTable, string|array $refColumns, string|null $delete = null, string|null $update = null): string

Builds a SQL statement for adding a foreign key constraint to an existing table.

The method will properly quote the table and column names.

Parameters

ParameterTypeDescription
$namestringThe name of the foreign key constraint.
$tablestringThe table that the foreign key constraint will be added to.
$columnsstring|arrayThe name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas or use an array to represent them.
$refTablestringThe table that the foreign key references to.
$refColumnsstring|arrayThe name of the column that the foreign key references to. If there are multiple columns, separate them with commas or use an array to represent them.
$deletestring|nullThe ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
$updatestring|nullThe ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL

Returns

string: The SQL statement for adding a foreign key constraint to an existing table.

public function addPrimaryKey(string $name, string $table, string|array $columns): string

Builds a SQL statement for adding a primary key constraint to an existing table.

Parameters

ParameterTypeDescription
$namestringThe name of the primary key constraint.
$tablestringThe table that the primary key constraint will be added to.
$columnsstring|arrayComma separated string or array of columns that the primary key will consist of.

Returns

string: The SQL statement for adding a primary key constraint to an existing table.

public function addUnique(string $name, string $table, string|array $columns): string

Creates a SQL command for adding an unique constraint to an existing table.

Parameters

ParameterTypeDescription
$namestringThe name of the unique constraint. The name will be properly quoted by the method.
$tablestringThe table that the unique constraint will be added to. The name will be properly quoted by the method.
$columnsstring|arrayThe name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas. The name will be properly quoted by the method.

Returns

string: The SQL statement for adding an unique constraint to an existing table.

Since

2.0.13

public function alterColumn(string $table, string $column, string $type): string

Builds a SQL statement for changing the definition of a column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be changed. The table name will be properly quoted by the method.
$columnstringThe name of the column to be changed. The name will be properly quoted by the method.
$typestringThe new column type. The getColumnType() method will be invoked to convert abstract column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. For example, ‘string’ will be turned into ‘varchar(255)’, while ‘string not null’ will become ‘varchar(255) not null’.

Returns

string: The SQL statement for changing the definition of a column.

public function batchInsert(string $table, array $columns, array|Generator $rows, array &$params = []): string

Generates a batch INSERT SQL statement.

For example,

$sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
]);

Note that the values in each row must match the corresponding column names.

The method will properly escape the column names, and quote the values to be inserted.

Parameters

ParameterTypeDescription
$tablestringThe table that new rows will be inserted into.
$columnsarrayThe column names
$rowsarray|GeneratorThe rows to be batch inserted into the table
$paramsarrayThe binding parameters. This parameter exists since 2.0.14

Returns

string: The batch INSERT SQL statement

public function bindParam(string|null $value, array &$params): string

Helper method to add $value to $params array using PARAM_PREFIX.

Parameters

ParameterTypeDescription
$valuestring|null
$paramsarrayPassed by reference

Returns

string: The placeholder name in $params array

Since

2.0.14

public function build(yii\db\Query $query, array $params = []): array

Generates a SELECT SQL statement from a Query object.

Parameters

ParameterTypeDescription
$queryQueryThe Query object from which the SQL statement will be generated.
$paramsarrayThe parameters to be bound to the generated SQL statement. These parameters will be included in the result with the additional parameters generated during the query building process.

Returns

array: The generated SQL statement (the first array element) and the corresponding parameters to be bound to the SQL statement (the second array element). The parameters returned include those provided in $params.

public function buildColumns(string|array $columns): string

Processes columns and properly quotes them if necessary.

It will join all columns into a string with comma as separators.

Parameters

ParameterTypeDescription
$columnsstring|arrayThe columns to be processed

Returns

string: The processing result

public function buildCondition(string|array|yii\db\ExpressionInterface $condition, array &$params): string

Parses the condition specification and generates the corresponding SQL expression.

Parameters

ParameterTypeDescription
$conditionstring|array|ExpressionInterfaceThe condition specification. Please refer to Query::where() on how to specify a condition.
$paramsarrayThe binding parameters to be populated

Returns

string: The generated SQL expression

public function buildExpression(yii\db\ExpressionInterface $expression, array &$params = []): string

Builds given $expression

Parameters

ParameterTypeDescription
$expressionExpressionInterfaceThe expression to be built
$paramsarrayThe parameters to be bound to the generated SQL statement. These parameters will be included in the result with the additional parameters generated during the expression building process.

Returns

string: The SQL statement that will not be neither quoted nor encoded before passing to DBMS

Throws

Since

2.0.14

See also

public function buildFrom(array $tables, array &$params): string

Parameters

ParameterTypeDescription
$tablesarray
$paramsarrayThe binding parameters to be populated

Returns

string: The FROM clause built from Query::$from.

public function buildGroupBy(array $columns): string

Parameters

ParameterTypeDescription
$columnsarray

Returns

string: The GROUP BY clause

public function buildHaving(string|array $condition, array &$params): string

Parameters

ParameterTypeDescription
$conditionstring|array
$paramsarrayThe binding parameters to be populated

Returns

string: The HAVING clause built from Query::$having.

public function buildJoin(array $joins, array &$params): string

Parameters

ParameterTypeDescription
$joinsarray
$paramsarrayThe binding parameters to be populated

Returns

string: The JOIN clause built from Query::$join.

Throws

  • Exception: if the $joins parameter is not in proper format
public function buildLimit(int $limit, int $offset): string

Parameters

ParameterTypeDescription
$limitint
$offsetint

Returns

string: The LIMIT and OFFSET clauses

public function buildOrderBy(array $columns): string

Parameters

ParameterTypeDescription
$columnsarray

Returns

string: The ORDER BY clause built from Query::$orderBy.

public function buildOrderByAndLimit(string $sql, array $orderBy, int $limit, int $offset): string

Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.

Parameters

ParameterTypeDescription
$sqlstringThe existing SQL (without ORDER BY/LIMIT/OFFSET)
$orderByarrayThe order by columns. See Query::orderBy() for more details on how to specify this parameter.
$limitintThe limit number. See Query::limit() for more details.
$offsetintThe offset number. See Query::offset() for more details.

Returns

string: The SQL completed with ORDER BY/LIMIT/OFFSET (if any)

public function buildSelect(array $columns, array &$params, bool $distinct = false, string|null $selectOption = null): string

Parameters

ParameterTypeDescription
$columnsarray
$paramsarrayThe binding parameters to be populated
$distinctbool
$selectOptionstring|null

Returns

string: The SELECT clause built from Query::$select.

public function buildUnion(array $unions, array &$params): string

Parameters

ParameterTypeDescription
$unionsarray
$paramsarrayThe binding parameters to be populated

Returns

string: The UNION clause built from Query::$union.

public function buildUnionOrderByAndLimit(string $sql, array<int|string, int|yii\db\ExpressionInterface>|null $orderBy, int|yii\db\ExpressionInterface|null $limit, int|yii\db\ExpressionInterface|null $offset): string

Builds the global ORDER BY and LIMIT/OFFSET clauses for a UNION query.

Parameters

ParameterTypeDescription
$sqlstringThe complete UNION SQL without global ORDER BY/LIMIT/OFFSET clauses.
$orderByarray<int|string, int|ExpressionInterface>|nullThe global order by columns.
$limitint|ExpressionInterface|nullThe global limit.
$offsetint|ExpressionInterface|nullThe global offset.

Returns

string: The completed UNION SQL.

Since

22.0

public function buildWhere(string|array $condition, array &$params): string

Parameters

ParameterTypeDescription
$conditionstring|array
$paramsarrayThe binding parameters to be populated

Returns

string: The WHERE clause built from Query::$where.

public function buildWithQueries(array $withs, array &$params): string

Parameters

ParameterTypeDescription
$withsarrayOf configurations for each WITH query
$paramsarrayThe binding parameters to be populated

Returns

string: Compiled WITH prefix of query including nested queries

Since

2.0.35

See also

public function checkIntegrity(bool $check = true, string $schema = '', string $table = ''): string

Builds a SQL statement for enabling or disabling integrity check.

Parameters

ParameterTypeDescription
$checkboolWhether to turn on or off the integrity check.
$schemastringThe schema of the tables. Defaults to empty string, meaning the current or default schema.
$tablestringThe table name. Defaults to empty string, meaning that no table will be changed.

Returns

string: The SQL statement for checking integrity

Throws

public function createConditionFromArray(string|array $condition): yii\db\conditions\ConditionInterface

Transforms $condition defined in array format (as described in Query::where() to instance of ConditionInterface according to $conditionClasses map.

Parameters

ParameterTypeDescription
$conditionstring|array

Returns

yii\db\conditions\ConditionInterface

Since

2.0.14

See also

public function createIndex(string $name, string $table, string|array $columns, bool $unique = false): string

Builds a SQL statement for creating a new index.

Parameters

ParameterTypeDescription
$namestringThe name of the index. The name will be properly quoted by the method.
$tablestringThe table that the new index will be created for. The table name will be properly quoted by the method.
$columnsstring|arrayThe column(s) that should be included in the index. If there are multiple columns, separate them with commas or use an array to represent them. Each column name will be properly quoted by the method, unless a parenthesis is found in the name.
$uniqueboolWhether to add UNIQUE constraint on the created index.

Returns

string: The SQL statement for creating a new index.

public function createTable(string $table, array $columns, string|null $options = null): string

Builds a SQL statement for creating a new DB table.

The columns in the new table should be specified as name-definition pairs (e.g. ‘name’ => ‘string’), where name stands for a column name which will be properly quoted by the method, and definition stands for the column type which must contain an abstract DB type. The getColumnType() method will be invoked to convert any abstract type into a physical one.

If a column is specified with definition only (e.g. ‘PRIMARY KEY (name, type)’), it will be directly inserted into the generated SQL.

For example,

$sql = $queryBuilder->createTable('user', [
'id' => 'pk',
'name' => 'string',
'age' => 'integer',
'column_name double precision null default null', # definition only example
]);

Parameters

ParameterTypeDescription
$tablestringThe name of the table to be created. The name will be properly quoted by the method.
$columnsarrayThe columns (name => definition) in the new table.
$optionsstring|nullAdditional SQL fragment that will be appended to the generated SQL.

Returns

string: The SQL statement for creating a new DB table.

public function createView(string $viewName, string|yii\db\Query $subQuery): string

Creates a SQL View.

Parameters

ParameterTypeDescription
$viewNamestringThe name of the view to be created.
$subQuerystring|QueryThe select statement which defines the view. This can be either a string or a Query object.

Returns

string: The CREATE VIEW SQL statement.

Since

2.0.14

public function delete(string $table, array|string $condition, array &$params): string

Creates a DELETE SQL statement.

For example,

$sql = $queryBuilder->delete('user', 'status = 0');

The method will properly escape the table and column names.

Parameters

ParameterTypeDescription
$tablestringThe table where the data will be deleted from.
$conditionarray|stringThe condition that will be put in the WHERE part. Please refer to Query::where() on how to specify condition.
$paramsarrayThe binding parameters that will be modified by this method so that they can be bound to the DB command later.

Returns

string: The DELETE SQL

public function dropCheck(string $name, string $table): string

Creates a SQL command for dropping a check constraint.

Parameters

ParameterTypeDescription
$namestringThe name of the check constraint to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose check constraint is to be dropped. The name will be properly quoted by the method.

Returns

string: The SQL statement for dropping a check constraint.

Since

2.0.13

public function dropColumn(string $table, string $column): string

Builds a SQL statement for dropping a DB column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be dropped. The name will be properly quoted by the method.
$columnstringThe name of the column to be dropped. The name will be properly quoted by the method.

Returns

string: The SQL statement for dropping a DB column.

public function dropCommentFromColumn(string $table, string $column): string

Builds a SQL command for adding comment to column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be commented. The table name will be properly quoted by the method.
$columnstringThe name of the column to be commented. The column name will be properly quoted by the method.

Returns

string: The SQL statement for adding comment on column

Since

2.0.8

public function dropCommentFromTable(string $table): string

Builds a SQL command for adding comment to table.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be commented. The table name will be properly quoted by the method.

Returns

string: The SQL statement for adding comment on column

Since

2.0.8

public function dropDefaultValue(string $name, string $table): string

Creates a SQL command for dropping a default value constraint.

Parameters

ParameterTypeDescription
$namestringThe name of the default value constraint to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose default value constraint is to be dropped. The name will be properly quoted by the method.

Returns

string: The SQL statement for dropping a default value constraint.

Throws

Since

2.0.13

public function dropForeignKey(string $name, string $table): string

Builds a SQL statement for dropping a foreign key constraint.

Parameters

ParameterTypeDescription
$namestringThe name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose foreign is to be dropped. The name will be properly quoted by the method.

Returns

string: The SQL statement for dropping a foreign key constraint.

public function dropIndex(string $name, string $table): string

Builds a SQL statement for dropping an index.

Parameters

ParameterTypeDescription
$namestringThe name of the index to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose index is to be dropped. The name will be properly quoted by the method.

Returns

string: The SQL statement for dropping an index.

public function dropPrimaryKey(string $name, string $table): string

Builds a SQL statement for removing a primary key constraint to an existing table.

Parameters

ParameterTypeDescription
$namestringThe name of the primary key constraint to be removed.
$tablestringThe table that the primary key constraint will be removed from.

Returns

string: The SQL statement for removing a primary key constraint from an existing table.

public function dropTable(string $table): string

Builds a SQL statement for dropping a DB table.

Parameters

ParameterTypeDescription
$tablestringThe table to be dropped. The name will be properly quoted by the method.

Returns

string: The SQL statement for dropping a DB table.

public function dropUnique(string $name, string $table): string

Creates a SQL command for dropping an unique constraint.

Parameters

ParameterTypeDescription
$namestringThe name of the unique constraint to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose unique constraint is to be dropped. The name will be properly quoted by the method.

Returns

string: The SQL statement for dropping an unique constraint.

Since

2.0.13

public function dropView(string $viewName): string

Drops a SQL View.

Parameters

ParameterTypeDescription
$viewNamestringThe name of the view to be dropped.

Returns

string: The DROP VIEW SQL statement.

Since

2.0.14

public function executeResetSequence(string $table, int|null $value = null): mixed

Execute a SQL statement for resetting the sequence value of a table’s primary key.

Reason for execute is that some databases (Oracle) need several queries to do so.

The sequence is reset such that the primary key of the next new row inserted will have the specified value or the maximum existing value +1.

Parameters

ParameterTypeDescription
$tablestringThe name of the table whose primary key sequence is reset.
$valueint|nullThe integer value for the primary key of the next new row inserted. If this is not set, the next new row’s primary key will have the maximum existing value +1.

Returns

mixed

Throws

Since

2.0.16

public function getColumnType(string|yii\db\ColumnSchemaBuilder $type): string

Converts an abstract column type into a physical column type.

The conversion is done using the type map specified in $typeMap. The following abstract column types are supported (using MySQL as an example to explain the corresponding physical types):

  • pk: an auto-incremental primary key type, will be converted into “int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY”
  • bigpk: an auto-incremental primary key type, will be converted into “bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY”
  • upk: an unsigned auto-incremental primary key type, will be converted into “int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY”
  • char: char type, will be converted into “char(1)”
  • string: string type, will be converted into “varchar(255)”
  • text: a long string type, will be converted into “text”
  • smallint: a small integer type, will be converted into “smallint(6)”
  • integer: integer type, will be converted into “int(11)”
  • bigint: a big integer type, will be converted into “bigint(20)”
  • boolean: boolean type, will be converted into “tinyint(1)”
  • `float“: float number type, will be converted into “float”
  • decimal: decimal number type, will be converted into “decimal”
  • datetime: datetime type, will be converted into “datetime”
  • timestamp: timestamp type, will be converted into “timestamp”
  • time: time type, will be converted into “time”
  • date: date type, will be converted into “date”
  • money: money type, will be converted into “decimal(19,4)”
  • binary: binary data type, will be converted into “blob”

If the abstract type contains two or more parts separated by spaces (e.g. “string NOT NULL”), then only the first part will be converted, and the rest of the parts will be appended to the converted result. For example, ‘string NOT NULL’ is converted to ‘varchar(255) NOT NULL’.

For some of the abstract types you can also specify a length or precision constraint by appending it in round brackets directly to the type. For example string(32) will be converted into “varchar(32)” on a MySQL database. If the underlying DBMS does not support these kind of constraints for a type it will be ignored.

If a type cannot be found in $typeMap, it will be returned without any change.

Parameters

ParameterTypeDescription
$typestring|ColumnSchemaBuilderAbstract column type

Returns

string: Physical column type.

public function getExpressionBuilder(yii\db\ExpressionInterface $expression): yii\db\ExpressionBuilderInterface

Gets object of ExpressionBuilderInterface that is suitable for $expression.

Uses $expressionBuilders array to find a suitable builder class.

Parameters

ParameterTypeDescription
$expressionExpressionInterface

Returns

ExpressionBuilderInterface

Throws

Since

2.0.14

See also

public function init(): mixed

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

Returns

mixed

public function insert(string $table, array|yii\db\Query $columns, array &$params): string

Creates an INSERT SQL statement.

For example,

$sql = $queryBuilder->insert('user', [
'name' => 'Sam',
'age' => 30,
], $params);

The method will properly escape the table and column names.

Parameters

ParameterTypeDescription
$tablestringThe table that new rows will be inserted into.
$columnsarray|QueryThe column data (name => value) to be inserted into the table or instance of Query to perform INSERT INTO … SELECT SQL statement. Passing of Query is available since version 2.0.11.
$paramsarrayThe binding parameters that will be generated by this method. They should be bound to the DB command later.

Returns

string: The INSERT SQL

public function renameColumn(string $table, string $oldName, string $newName): string

Builds a SQL statement for renaming a column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be renamed. The name will be properly quoted by the method.
$oldNamestringThe old name of the column. The name will be properly quoted by the method.
$newNamestringThe new name of the column. The name will be properly quoted by the method.

Returns

string: The SQL statement for renaming a DB column.

public function renameTable(string $oldName, string $newName): string

Builds a SQL statement for renaming a DB table.

Parameters

ParameterTypeDescription
$oldNamestringThe table to be renamed. The name will be properly quoted by the method.
$newNamestringThe new table name. The name will be properly quoted by the method.

Returns

string: The SQL statement for renaming a DB table.

public function resetSequence(string $tableName, int|null $value = null): string

Creates a SQL statement for resetting the sequence value of a table’s primary key.

The sequence will be reset such that the primary key of the next new row inserted will have the specified value or the maximum existing value +1.

Parameters

ParameterTypeDescription
$tableNamestringThe name of the table whose primary key sequence will be reset.
$valueint|nullThe integer value for the primary key of the next new row inserted. If this is not set, the next new row’s primary key will have the maximum existing value +1.

Returns

string: The SQL statement for resetting sequence.

Throws

public function selectExists(string $rawSql): string

Creates a SELECT EXISTS() SQL statement.

Parameters

ParameterTypeDescription
$rawSqlstringThe subquery in a raw form to select from.

Returns

string: The SELECT EXISTS() SQL statement.

Since

2.0.8

public function setConditionClasses(string[] $classes): mixed

Setter for $conditionClasses property.

Parameters

ParameterTypeDescription
$classesstring[]Map of condition aliases to condition classes. For example: [‘LIKE’ => yii\db\condition\LikeCondition::class]

Returns

mixed

Since

2.0.14.2

See also

public function setExpressionBuilders(string[] $builders): mixed

Setter for $expressionBuilders property.

Parameters

ParameterTypeDescription
$buildersstring[]Array of builders that should be merged with the pre-defined ones in $expressionBuilders property.

Returns

mixed

Since

2.0.14

See also

public function truncateTable(string $table): string

Builds a SQL statement for truncating a DB table.

Parameters

ParameterTypeDescription
$tablestringThe table to be truncated. The name will be properly quoted by the method.

Returns

string: The SQL statement for truncating a DB table.

public function update(string $table, array $columns, array|string $condition, array &$params): string

Creates an UPDATE SQL statement.

For example,

$params = [];
$sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);

The method will properly escape the table and column names.

Parameters

ParameterTypeDescription
$tablestringThe table to be updated.
$columnsarrayThe column data (name => value) to be updated.
$conditionarray|stringThe condition that will be put in the WHERE part. Please refer to Query::where() on how to specify condition.
$paramsarrayThe binding parameters that will be modified by this method so that they can be bound to the DB command later.

Returns

string: The UPDATE SQL

public function upsert(string $table, array|yii\db\Query $insertColumns, array|bool $updateColumns, array &$params): string

Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique constraints), or update them if they do.

For example,

$sql = $queryBuilder->upsert('pages', [
'name' => 'Front page',
'url' => 'https://example.com/', // url is unique
'visits' => 0,
], [
'visits' => new \yii\db\Expression('visits + 1'),
], $params);

The method will properly escape the table and column names.

Parameters

ParameterTypeDescription
$tablestringThe table that new rows will be inserted into/updated in.
$insertColumnsarray|QueryThe column data (name => value) to be inserted into the table or instance of Query to perform INSERT INTO ... SELECT SQL statement.
$updateColumnsarray|boolThe column data (name => value) to be updated if they already exist. If true is passed, the column data will be updated to match the insert column data. If false is passed, no update will be performed if the column data already exists.
$paramsarrayThe binding parameters that will be generated by this method. They should be bound to the DB command later.

Returns

string: The resulting SQL.

Throws

Since

2.0.14

protected function concatUnionSql(string $sql, string $union): string

Concatenates the first SELECT statement with the UNION clauses built by buildUnion().

Parameters

ParameterTypeDescription
$sqlstringThe SQL of the first SELECT statement.
$unionstringThe UNION clauses.

Returns

string: The compound SQL with the first statement parenthesized.

Since

22.0

protected function defaultConditionClasses(): array

Contains array of default condition classes. Extend this method, if you want to change default condition classes for the query builder. See $conditionClasses docs for details.

Returns

array

Since

2.0.14

See also

protected function defaultExpressionBuilders(): array

Contains array of default expression builders. Extend this method and override it, if you want to change default expression builders for this query builder. See $expressionBuilders docs for details.

Returns

array

Since

2.0.14

See also

protected function extractAlias(mixed $table): bool|array

Extracts table alias if there is one or returns false

Parameters

ParameterTypeDescription
$tablemixed

Returns

bool|array

Since

2.0.24

protected function hasLimit(mixed $limit): bool

Checks to see if the given limit is effective.

Parameters

ParameterTypeDescription
$limitmixedThe given limit

Returns

bool: Whether the limit is effective

protected function hasOffset(mixed $offset): bool

Checks to see if the given offset is effective.

Parameters

ParameterTypeDescription
$offsetmixedThe given offset

Returns

bool: Whether the offset is effective

protected function prepareInsertSelectSubQuery(yii\db\Query $columns, yii\db\Schema $schema, array $params = []): array

Prepare select-subquery and field names for INSERT INTO … SELECT SQL statement.

Parameters

ParameterTypeDescription
$columnsQueryObject, which represents select query.
$schemaSchemaSchema object to quote column name.
$paramsarrayThe parameters to be bound to the generated SQL statement. These parameters will be included in the result with the additional parameters generated during the query building process.

Returns

array: Array of column names, values and params.

Throws

Since

2.0.11

protected function prepareInsertValues(string $table, array|yii\db\Query $columns, array $params = []): array

Prepares a VALUES part for an INSERT SQL statement.

Parameters

ParameterTypeDescription
$tablestringThe table that new rows will be inserted into.
$columnsarray|QueryThe column data (name => value) to be inserted into the table or instance of Query to perform INSERT INTO … SELECT SQL statement.
$paramsarrayThe binding parameters that will be generated by this method. They should be bound to the DB command later.

Returns

array: Array of column names, placeholders, values and params.

Since

2.0.14

protected function prepareSelectQuery(yii\db\Query $query): yii\db\Query

Performs driver-specific preparation after Query::prepare().

Implementations must not modify the given query; they must return a modified clone instead.

Parameters

ParameterTypeDescription
$queryQueryThe prepared query.

Returns

Query: The query to build.

Since

22.0

protected function prepareUpdateSets(string $table, array $columns, array $params = []): array

Prepares a SET parts for an UPDATE SQL statement.

Parameters

ParameterTypeDescription
$tablestringThe table to be updated.
$columnsarrayThe column data (name => value) to be updated.
$paramsarrayThe binding parameters that will be modified by this method so that they can be bound to the DB command later.

Returns

array: An array SET parts for an UPDATE SQL statement (the first array element) and params (the second array element).

Since

2.0.14

protected function prepareUpsertColumns(string $table, array|yii\db\Query $insertColumns, array|bool $updateColumns, yii\db\Constraint[] &$constraints = []): array

Parameters

ParameterTypeDescription
$tablestring
$insertColumnsarray|Query
$updateColumnsarray|bool
$constraintsConstraint[]This parameter receives a matched constraint list. The constraints will be unique by their column names.

Returns

array

Since

2.0.14

protected function prepareUpsertSets(string $table, array<string, mixed>|bool $updateColumns, string[]|null $updateNames, array<string, mixed> $params, Closure(string): string $sourceColumnRef): array{string[], array<string, mixed>}

Prepares the SET assignments for the update branch of an upsert statement.

Parameters

ParameterTypeDescription
$tablestringThe table that the upsert targets.
$updateColumnsarray<string, mixed>|booltrue for every non-unique inserted column, or an explicit name => value map.
$updateNamesstring[]|nullQuoted column names eligible for update.
$paramsarray<string, mixed>The binding parameters modified by this method.
$sourceColumnRefClosure(string): stringMaps a quoted column name to its source reference.

Returns

array{string[], array<string, mixed>}: The SET assignments (first element) and params (second element).

Since

22.0