Consult on Yii2 database transaction code

What’s your opinion about this snippet code? (I’ve wrote some questions in comments of code)

function training($model_1, $model_2)
{
    $transaction = Discount::getDb()->beginTransaction();
    try {
        $result = true;

        if (!$model_1->save()) {
            $result = false; // Can i use here "return false;" instead?
        }

        if ($result) {
            if(!$model_2->save()) {
                $result = false; // or there can i use here "return false;" instead?
            }
        }

        if ($result) {
            $transaction->commit();
            return $result;
        }

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

    $transaction->rollBack(); // rollback in here is need?
    return $result;
}

I would rather throw an exception in every case. You don’t need $result then at all. And definitely you don’t need last rollback.

function training($model_1, $model_2)
{
    $transaction = Discount::getDb()->beginTransaction();
    try {
        if (!$model_1->save()) {
            throw new \Exception('Model1 saving error');
        }

        if (!$model_2->save()) {
            throw new \Exception('Model2 saving error');
        }

        $transaction->commit();
        return true;
    } catch (\Throwable $e) {
        $transaction->rollBack();
    }

    return false;
}
1 Like

So after beginTransaction() is not necessary to recall commit() or rollBack() ?

@Bizley I want to return suitable message to end-user and give him other chance to try again.

If you don’t call the commit function your changes won’t be applied to your DB. So when you exit the core previously (by returning something for example) the changes are not applied but it’s better to throw an exception and do the rollback.

1 Like

I know it, but I want nothing query is left inside the transaction for the next possible transactions, before end of process the current script.
Indeed is need to empty the queue of transportation? If yes, how do I do that?

You can clear the “queue” and ensure nothing is left by doing the rollback.

1 Like