M
M
McMike2019-07-22 08:22:23
Yii
McMike, 2019-07-22 08:22:23

How to properly delete models inside a transaction?

I open a transaction, then I do ->delete() on the model.
Then I do a rollback, but as a result, the data in the database is deleted.
How to properly use model deletion and transactions?

$transaction = \Yii::$app->db->beginTransaction();
        try {
            $params = Param::findAll(['type_id' => $typeId]);
            foreach ($params as $param) {
                if (!$param->delete()) {
                    throw new Exception('deleting error');
                }
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->error('Transaction rollback with error - ' . $e->getMessage());
        }

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
eternalfire, 2019-07-22
@eternalfire

Hey!
In general terms, so

$transaction = $connection->beginTransaction();
try {
    $model->delete();
    $transaction->commit();
} catch (\Exception $e) {
    $transaction->rollBack();
    throw $e;
}

or
$transaction = $connection->beginTransaction();
if ($model->delete()) {
    $transaction->commit();
} else {
    $transaction->rollBack();
}

K
Kolya K, 2017-11-01
@Kolyagrozamorey

Connect another monitor and it will immediately be clear whether it is the case or the system unit. Very similar to a burned out backlight or a defective backlight power supply.

R
Rastachiter, 2017-11-01
@Rastachiter

plug the monitor into the port of the built-in video adapter, so it will be clear - a monitor or a vidyuha.

Z
zooks, 2017-11-01
@zooks

Vidyuha, or mother, or RAM.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question