Answer the question
In order to leave comments, you need to log in
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;
}
}
if ($model->load($_POST) && $this->applyOperation($model) ) {
//return $this->redirect( куда то там )
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question