Yii Framework 2 : Upsert Query

Upsert is an atomic operation. `Upsert()` will insert new record into a database table If table do not already exist or update them.


upsert( $table, $insertColumns, $updateColumns = true, $params = [])
Using QueryBuilder

$sql = $queryBuilder->upsert('pages', [
    'name' => 'Home page',
    'url' => 'https://bsourcecode.com/', // url is unique
    'visits' => 10000,
], [
    'visits' => new \yii\db\Expression('visits + 1'),
], $params = array());
Using Command:

Yii::$app->db->createCommand()->upsert('pages', [
    'name' => 'Home page',
    'url' => 'https://bsourcecode.com/', // url is unique
    'visits' => 10000,
], [
    'visits' => new \yii\db\Expression('visits + 1'),
], $params)->execute();

This code will either insert a new record in database or update the visits column.

 

Leave a Reply

Your email address will not be published. Required fields are marked *