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::batchInsert()
method:
<?php
declare(strict_types=1);
use Yiisoft\Db\Connection\ConnectionInterface;
/** @var ConnectionInterface $db */
$db->createCommand()->batchInsert(
'{{%customer}}',
['name', 'email'],
[
['user1', '[email protected]'],
['user2', '[email protected]'],
['user3', '[email protected]'],
]
)->execute();
To delete rows from a table, you can use the Yiisoft\Db\Command\CommandInterface::delete()
method:
<?php
declare(strict_types=1);
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:
<?php
declare(strict_types=1);
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:
<?php
declare(strict_types=1);
use Yiisoft\Db\Connection\ConnectionInterface;
/** @var ConnectionInterface $db */
$db->createCommand()->insert('{{%customer}}', ['name' => 'John', 'age' => 18])->execute();
To update rows in a table, you can use the Yiisoft\Db\Command\CommandInterface::update()
method:
<?php
declare(strict_types=1);
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:
<?php
declare(strict_types=1);
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();