I want to make transactions in Yii2
found such an example
Private Function ApplyOperation ($ model)
{
// Change the balance of the counterparty
$ Contragent = Contragents :: Find ($ Model- & GT; Contragent);
$ Contragent- & GT; Balance = $ Contragent- & GT; Balance + $ Model- & GT; Prihod;
$ Contragent- & GT; Balance = $ Contragent- & GT; Balance - $ Model- & GT; Rashod;
// Remember the current balance of counterparty
$ model- & gt; balance = $ contragent- & gt; balance;
// Save both the model of operation and the counterparty model
$ transaction = yii :: $ app- & gt; db- & gt; beginransaction ();
if ($ contragent- & gt; save () & amp; & amp; $ model- & gt; save ()) {
// If saving has passed without errors, then commitimit transaction
$ transaction- & gt; commit ();
RETURN TRUE;
} else {
// If at least one of the preservations failed, you roll back
$ transaction- & gt; rollback ();
RETURN FALSE;
}
}
action
if ($ model- & gt; load ($ _ post) & amp; & amp; $ this- & gt; applyoperation ($ model) ) {
// Return $ this- & gt; redirect (somewhere there)
}
Tell me how to write a view of the views?
I can not understand there one variable $ contragent, and I need to take one user to pick up from the balance, add another.
Answer 1, Authority 100%
Transaction task to ensure the execution of a series of SQL queries as one atomic operation.
In the example, all operations with ActiveRecord and the database inside the TRY block to the commote will be performed in the transaction. In case of error, no change is recorded in the database.
An example from the documentation :
$ transaction = $ Connection- & gt; beginransaction ();
Try {
$ Connection- & GT; CreateCommand ($ SQL1) - & gt; execute ();
$ Connection- & GT; CreateCommand ($ SQL2) - & gt; execute ();
// .... Other SQL Executions
$ transaction- & gt; commit ();
} Catch (\ Exception $ E) {
$ transaction- & gt; rollback ();
Throw $ E;
}