diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index a01b0b2dee..8ecee19b49 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -77,7 +77,7 @@ Yii Framework 2 Change Log - Enh #13618: Active record now resets related models after corresponding attributes updates (Kolyunya, rob006) - Enh #13679: Added `yii\behaviors\CacheableWidgetBehavior` (Kolyunya) - Enh #13814: MySQL unique index names can now contain spaces (df2) -- Enh #13879: Added upsert support for `yii\db\QueryBuilder` and `yii\db\Command` (sergeymakinen) +- Enh #13879: Added upsert support for `yii\db\QueryBuilder`, `yii\db\Command`, and `yii\db\Migration` (sergeymakinen) - Enh #13919: Added option to add comment for created table to migration console command (mixartemev, developeruz) - Enh #13996: Added `yii\web\View::registerJsVar()` method that allows registering JavaScript variables (Eseperio, samdark) - Enh #14043: Added `yii\helpers\IpHelper` (silverfire, cebe) diff --git a/framework/db/Migration.php b/framework/db/Migration.php index 41e9a3d049..a144d4a43f 100644 --- a/framework/db/Migration.php +++ b/framework/db/Migration.php @@ -247,6 +247,30 @@ class Migration extends Component implements MigrationInterface $this->endCommand($time); } + /** + * Creates and executes a command to insert rows into a database table if + * they do not already exist (matching unique constraints), + * or update them if they do. + * + * The method will properly escape the column names, and bind the values to be inserted. + * + * @param string $table the table that new rows will be inserted into/updated in. + * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance + * of [[Query]] to perform `INSERT INTO ... SELECT` SQL statement. + * @param array|bool $updateColumns 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. + * @param array $params the parameters to be bound to the command. + * @return $this the command object itself. + * @since 2.0.14 + */ + public function upsert($table, $insertColumns, $updateColumns = true, $params = []) + { + $time = $this->beginCommand("upsert into $table"); + $this->db->createCommand()->upsert($table, $insertColumns, $updateColumns, $params)->execute(); + $this->endCommand($time); + } + /** * Creates and executes an UPDATE SQL statement. * The method will properly escape the column names and bind the values to be updated.