Search code examples
activerecordyii2transactions

how to make multiple delete or update or insert in one transaction in yii2 using active records


is it the right way in my code to do multiple statement in one transaction using active records? cause I don't know how to make it like that please advice, thanks enter image description here


Solution

  • 
    $transaction = Yii::$app->db->beginTransaction();
    try {
        //.... active record operations
        $transaction->commit();
    } catch (\Exception $e) {
        $transaction->rollBack();
        throw $e;
    } catch (\Throwable $e) {
        $transaction->rollBack();
        throw $e;
    }
    
    

    Note from Yii2 doc: in the above code we have two catch-blocks for compatibility with PHP 5.x and PHP 7.x. \Exception implements the \Throwable interface since PHP 7.0, so you can skip the part with \Exception if your app uses only PHP 7.0 and higher.

    References: