S
S
Sergey2015-05-12 23:28:11
Yii
Sergey, 2015-05-12 23:28:11

How to make transactions in Yii2?

Hi all.
I want to make transactions in Yii2
Found this example

private function applyOperation($model)
{
            //изменяем баланс контрагента
            $contragent= Contragents::find( $model->contragent );   
            $contragent->balance = $contragent->balance + $model->prihod;
            $contragent->balance = $contragent->balance - $model->rashod;            
            
            //запомним в операции текущий баланс контрагента
            $model->balance=$contragent->balance;            

            //сохраним и модель операции и модель контрагента
            $transaction = Yii::$app->db->beginTransaction();
if ($contragent->save() && $model->save()) {
    // если сохранение прошло без ошибок, то коммитим транзакцию
    $transaction->commit();
    return true;
} else {
    // если хоть одно из сохранений не удалось, то откатываемся
    $transaction->rollback();
    return false;
}
}

Action
if ($model->load($_POST) && $this->applyOperation($model) ) {
    //return $this->redirect(  куда то там )
}

Tell me how to write the form of the view?
I can’t understand in any way there is one variable $contragent, but I need to take it from the balance of one user and
add it to another.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
restyler, 2015-05-12
@restyler

In the example, one of the users is registered in the relation ($user->contragent - so you need to look at the Contragent::getContragent() method) - this means that it is assumed that it is already in the database, or (more likely) it is loaded from $_POST (i.e. in the form in the view there is a user[contragent_id] field that is filled in by the user in the browser)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question