Command

Type
Class
Namespace
craft\db
Inherits
craft\db\Command » yii\db\Command » yii\base\Component » yii\base\BaseObject
Implements
yii\base\Configurable
Since
3.0

View source

Public Properties

PropertyDescription
$behaviorsyii\base\Behavior – List of behaviors attached to this component
$dbyii\db\Connection – The DB connection that this command is associated with
$fetchModeinteger – The default fetch mode for this command.
$paramsarray – The parameters (name => value) that are bound to the current PDO statement.
$pdoStatementPDOStatement – The PDOStatement object that this command is associated with
$queryCacheDependencyyii\caching\Dependency – The dependency to be associated with the cached query result for this command
$queryCacheDurationinteger – The default number of seconds that query results can remain valid in cache.
$rawSqlstring – The SQL statement to be set.
$sqlstring – The SQL statement to be executed

Public Methods

MethodDescription
__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 an object property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets value of an object property.
__unset()Sets an object property to null.
addCheck()Creates a SQL command for adding a check constraint to an existing table.
addColumn()Creates a SQL command for adding a new DB column.
addCommentOnColumn()Builds a SQL command for adding comment to column.
addCommentOnTable()Builds a SQL command for adding comment to table.
addDefaultValue()Creates a SQL command for adding a default value constraint to an existing table.
addForeignKey()Creates a SQL command for adding a foreign key constraint to an existing table.
addPrimaryKey()Creates a SQL command for adding a primary key constraint to an existing table.
addUnique()Creates a SQL command for adding an unique constraint to an existing table.
alterColumn()Creates a SQL command for changing the definition of a column.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
batchInsert()Creates a batch INSERT command.
behaviors()Returns a list of behaviors that this component should behave as.
bindParam()Binds a parameter to the SQL statement to be executed.
bindValue()Binds a value to a parameter.
bindValues()Binds a list of values to the corresponding parameters.
cache()Enables query cache for this command.
canGetProperty()Returns a value indicating whether a property can be read.
canSetProperty()Returns a value indicating whether a property can be set.
cancel()Cancels the execution of the SQL statement.
checkIntegrity()Builds a SQL command for enabling or disabling integrity check.
className()Returns the fully qualified name of this class.
createIndex()Creates a SQL command for creating a new index.
createTable()Creates a SQL command for creating a new DB table.
createView()Creates a SQL View.
delete()Creates a DELETE command.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
dropCheck()Creates a SQL command for dropping a check constraint.
dropColumn()Creates a SQL command for dropping a DB column.
dropCommentFromColumn()Builds a SQL command for dropping comment from column.
dropCommentFromTable()Builds a SQL command for dropping comment from table.
dropDefaultValue()Creates a SQL command for dropping a default value constraint.
dropForeignKey()Creates a SQL command for dropping a foreign key constraint.
dropIndex()Creates a SQL command for dropping an index.
dropPrimaryKey()Creates a SQL command for removing a primary key constraint to an existing table.
dropTable()Creates a SQL command for dropping a DB table.
dropTableIfExists()Creates a SQL statement for dropping a DB table, if it exists.
dropUnique()Creates a SQL command for dropping an unique constraint.
dropView()Drops a SQL View.
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.
execute()Executes the SQL statement.
getBehavior()Returns the named behavior object.
getBehaviors()Returns all behaviors attached to this component.
getRawSql()Returns the raw SQL by inserting parameter values into the corresponding placeholders in $sql.
getSql()Returns the SQL statement for this command.
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.
init()Initializes the object.
insert()Creates an INSERT command.
noCache()Disables query cache for this command.
off()Detaches an existing event handler from this component.
on()Attaches an event handler to an event.
prepare()Prepares the SQL statement to be executed.
query()Executes the SQL statement and returns query result.
queryAll()Executes the SQL statement and returns ALL rows at once.
queryColumn()Executes the SQL statement and returns the first column of the result.
queryOne()Executes the SQL statement and returns the first row of the result.
queryScalar()Executes the SQL statement and returns the value of the first column in the first row of data.
renameColumn()Creates a SQL command for renaming a column.
renameSequence()Creates a SQL statement for renaming a DB sequence.
renameTable()Creates a SQL command for renaming a DB table.
replace()Creates a SQL statement for replacing some text with other text in a given table column.
resetSequence()Creates a SQL command for resetting the sequence value of a table's primary key.
setRawSql()Specifies the SQL statement to be executed. The SQL statement will not be modified in any way.
setSql()Specifies the SQL statement to be executed. The SQL statement will be quoted using craft\db\Connection::quoteSql().
trigger()Triggers an event.
truncateTable()Creates a SQL command for truncating a DB table.
update()Creates an UPDATE command.
upsert()Creates a command to insert rows into a database table if they do not already exist (matching unique constraints), or update them if they do.

batchInsert()

Creates a batch INSERT command.

For example,

$connection->createCommand()->batchInsert('user', ['name', 'age'], [
    ['Tom', 30],
    ['Jane', 20],
    ['Linda', 25],
])->execute();

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

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

Also note that the created command is not executed until execute() is called.

View source

Arguments

  • $table (string) – The table that new rows will be inserted into.
  • $columns (array) – The column names.
  • $rows (array) – The rows to be batch inserted into the table.
  • $includeAuditColumns (boolean) – Whether dateCreated, dateUpdated, and uid values should be added to $columns.

Returns

static – The command object itself.

Signature

public static batchInsert ( $table, $columns, $rows, $includeAuditColumns = true )

dropTableIfExists()

Creates a SQL statement for dropping a DB table, if it exists.

View source

Arguments

  • $table (string) – The table to be dropped. The name will be properly quoted by the method.

Returns

craft\db\Command – The command object itself

Signature

public craft\db\Command dropTableIfExists ( \craft\db\string $table )

insert()

Creates an INSERT command.

For example,

$connection->createCommand()->insert('user', [
    'name' => 'Sam',
    'age' => 30,
])->execute();

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

Note that the created command is not executed until execute() is called.

View source

Arguments

  • $table (string) – The table that new rows will be inserted into.
  • $columns (array) – The column data (name => value) to be inserted into the table.
  • $includeAuditColumns (boolean) – Whether dateCreated, dateUpdated, and uid values should be added to $columns.

Returns

static – The command object itself

Signature

public static insert ( $table, $columns, $includeAuditColumns = true )

renameSequence()

Creates a SQL statement for renaming a DB sequence.

View source

Arguments

  • $oldName (string) – The sequence to be renamed. The name will be properly quoted by the method.
  • $newName (string) – The new sequence name. The name will be properly quoted by the method.

Returns

craft\db\Command – The command object itself

Signature

public craft\db\Command renameSequence ( \craft\db\string $oldName, \craft\db\string $newName )

replace()

Creates a SQL statement for replacing some text with other text in a given table column.

View source

Arguments

  • $table (string) – The table to be updated.
  • $column (string) – The column to be searched.
  • $find (string) – The text to be searched for.
  • $replace (string) – The replacement text.
  • $condition (string, array) – The condition that will be put in the WHERE part. Please refer to craft\db\Query::where() on how to specify condition.
  • $params (array) – The parameters to be bound to the command.

Returns

craft\db\Command – The command object itself.

Signature

public craft\db\Command replace ( \craft\db\string $table, \craft\db\string $column, \craft\db\string $find, \craft\db\string $replace, $condition = '', array $params = [] )

update()

Creates an UPDATE command.

For example,

$connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();

or with using parameter binding for the condition:

$minAge = 30;
$connection->createCommand()->update('user', ['status' => 1], 'age > :minAge', [':minAge' => $minAge])->execute();

The method will properly escape the column names and bind the values to be updated.

Note that the created command is not executed until execute() is called.

View source

Arguments

  • $table (string) – The table to be updated.
  • $columns (array) – The column data (name => value) to be updated.
  • $condition (string, array) – The condition that will be put in the WHERE part. Please refer to craft\db\Query::where() on how to specify condition.
  • $params (array) – The parameters to be bound to the command.
  • $includeAuditColumns (boolean) – Whether the dateUpdated value should be added to $columns.

Returns

static – The command object itself.

Signature

public static update ( $table, $columns, $condition = '', $params = [], $includeAuditColumns = true )

upsert()

Creates a command 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' => 'http://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.

View source

Arguments

  • $table (string) – The table that new rows will be inserted into/updated in.
  • $insertColumns (array, craft\db\Query) – The column data (name => value) to be inserted into the table or instance of craft\db\Query to perform INSERT INTO ... SELECT SQL statement.
  • $updateColumns (array, boolean) – The 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.
  • $params (array) – The parameters to be bound to the command.
  • $includeAuditColumns (boolean) – Whether dateCreated, dateUpdated, and uid values should be added to $columns.

Returns

$this – The command object itself.

Signature

public $this upsert ( $table, $insertColumns, $updateColumns = true, $params = [], \craft\db\bool $includeAuditColumns = true )

Protected Methods

MethodDescription
bindPendingParams()Binds pending parameters that were registered via bindValue() and bindValues().
internalExecute()Executes a prepared statement.
queryInternal()Performs the actual DB query of a SQL statement.
refreshTableSchema()Refreshes table schema, which was marked by requireTableSchemaRefresh().
requireTableSchemaRefresh()Marks a specified table schema to be refreshed after command execution.
requireTransaction()Marks the command to be executed in transaction.
reset()Resets command properties to their initial state.
setRetryHandler()Sets a callable (e.g. anonymous function) that is called when \craft\db\Exception is thrown when executing the command. The signature of the callable should be: