Yii2 php recycle mysql transactions

hi, Hello, everyone.
there are now ten pieces of data that need to be inserted and ten pieces of data that need to be updated. The data that needs to be inserted in suspense is a1memery a2magina3.a10, and the data that needs to be updated is b1memb2recoverb3.b10.

you need to ensure that all data operations succeed or fail at the same time. (that is, transactions).
and you need to update the primary key ID of A1 to a field of b1, a2 to a field of b2, and so on.

what I"m doing now is:

foreach($arr_a AS $a){
    //
    // a1  id1
    //ID b1
    //
}

but there are several problems with this:
(1) does using transactions in a loop cause performance problems?
(2) if an exception is thrown, some data cannot be manipulated. The outermost layer plus business?

does the Great God have any good solutions? For guidance ~ Thank you very much!


you need to ensure that all data operations succeed or fail at the same time. does it mean that if the A10 operation fails, all the data will be rolled back before the A1 operation? If that's the case, of course it is. The transaction is best placed on the outer layer of the loop.

if only "a field of the primary key ID after A1 insertion is updated to b1" is a transaction, and the failure of any set of operations does not affect other group operations, the transaction should be placed in a loop.

// key
$error = [];

foreach($arr_a AS $key => $a){
    $transaction = Yii::$app->getDb()->beginTransaction();

    try {
        // a1  id1
        //ID b1
        
        $transaction->commit();
    } catch (\Exception $e) {

        // 
        $transaction->rollBack();
        // key
        $error[] = $key;

        // 
        continue;
    }
}

//  $error 

transaction locks are performance-intensive, so it's best to put transactions on the outside of the loop so that you can succeed or fail together.

Menu