TheStoryCoder
TheStoryCoder

Reputation: 3640

Yii2: Execute query outside transaction?

I need to run a query outside the transaction that I have started:

$transaction = \Yii::$app->db->beginTransaction();
try {

    //... other database queries within the transaction ...

    //Query I want to be inserted regardless:
    \Yii::$app->db->createCommand("INSERT INTO...")->execute();

    $transaction->commit();
} catch (\Exception $e) {
    $transaction->rollBack();
    throw $e;
}

Is there a smart way to do that, or do I need to clone/create a new database connection - and if so, what's the best way to do that without having to specify the database parameters again and just use the same config?

Upvotes: 1

Views: 712

Answers (1)

rob006
rob006

Reputation: 22174

You need to use separate connection or move this query after/before transaction.

For copying DB component you can simply use clone - new instance should open new connection on first query:

$connection = clone Yii::$app->db;
$connection->createCommand("INSERT INTO...")->execute();

It is used in this way in yii\log\DbTarget.

But you may consider declaring separate DB component for this task (Yii::$app->db2) - then you will be able to reuse this additional connection.

Upvotes: 2

Related Questions