DML is a set of SQL statements used to manipulate data in a database.
You can use the DML to perform the following operations:
To insert multiple rows into a table, you can use the Yiisoft\Db\Command\CommandInterface::insertBatch()
method:
use Yiisoft\Db\Connection\ConnectionInterface;
/** @var ConnectionInterface $db */
$db->createCommand()->insertBatch(
'{{%customer}}',
[
['user1', 'email1@email.com'],
['user2', 'email2@email.com'],
['user3', 'email3@email.com'],
],
['name', 'email'],
)->execute();
It is possible to insert rows as associative arrays, where the keys are column names.
use Yiisoft\Db\Connection\ConnectionInterface;
/** @var ConnectionInterface $db */
$db->createCommand()->insertBatch(
'{{%customer}}',
[
['name' => 'user1', 'email' => 'email1@email.com'],
['name' => 'user2', 'email' => 'email2@email.com'],
['name' => 'user3', 'email' => 'email3@email.com'],
],
)->execute();
To delete rows from a table, you can use the Yiisoft\Db\Command\CommandInterface::delete()
method:
use Yiisoft\Db\Connection\ConnectionInterface;
/** @var ConnectionInterface $db */
$db->createCommand()->delete('{{%customer}}', ['id' => 1])->execute();
To reset the sequence of a table, you can use the Yiisoft\Db\Command\CommandInterface::resetSequence()
method:
use Yiisoft\Db\Connection\ConnectionInterface;
/** @var ConnectionInterface $db */
$db->createCommand()->resetSequence('{{%customer}}', 1)->execute();
To insert a row to a table, you can use the Yiisoft\Db\Command\CommandInterface::insert()
method:
use Yiisoft\Db\Connection\ConnectionInterface;
/** @var ConnectionInterface $db */
$db->createCommand()->insert('{{%customer}}', ['name' => 'John Doe', 'age' => 18])->execute();
To update rows in a table, you can use the Yiisoft\Db\Command\CommandInterface::update()
method:
use Yiisoft\Db\Connection\ConnectionInterface;
/** @var ConnectionInterface $db */
$db->createCommand()->update('{{%customer}}', ['status' => 2], ['id' > 1])->execute();
To atomically update existing rows and insert non-existing ones,
you can use the Yiisoft\Db\Command\CommandInterface::upsert()
method:
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Expression\Expression;
/** @var ConnectionInterface $db */
$db->createCommand()->upsert(
'pages',
[
'name' => 'Front page',
'url' => 'https://example.com/', // URL is unique
'visits' => 0,
],
updateColumns: [
'visits' => new Expression('visits + 1'),
],
params: $params,
)->execute();