Answer the question
In order to leave comments, you need to log in
Yii2: How to perform an append to a single table with transaction mode enabled?
Hello. There is adding some split data, here is an example:
asddasd|asdasd|hhasd|sadasd
hhsadasd|hhjaskdkasd|asdlasd
That is, just a few rows that need to be added to one table.
Implemented like this, but doesn't work:
$data = explode("\n", $this->data);
$transaction = $this->getDb()->beginTransaction();
try {
for ($i=0; $i<count($data ); $i++) {
$array= explode("|", $data[$i]);
$this->login = $array[0];
$this->password = (isset($array[1])) ? $array[1] : '';
$this->proxy = (isset($array[2]) && isset($array[3])) ? $array[2].$array[3] : '';
if (!$this->save()) {
$transaction->rollBack();
foreach ($this->firstErrors as $key => $value) break;
if (empty($value)) $value = 'Неизвестная ошибка';
return array('message' => $value, 'status' => false);
}
#}
}
$transaction->commit();
} catch(\Exception $e) {
$transaction->rollBack();
throw $e;
}
Answer the question
In order to leave comments, you need to log in
This is
$transaction->rollBack();
foreach ($this->firstErrors as $key => $value) break;
if (empty($value)) $value = 'Неизвестная ошибка';
return array('message' => $value, 'status' => false);
The try-catch construct assumes that in the try block, one of the operations can throw an exception, which will be handled by the catch block. In your code, none of the operations explicitly throw an exception, so there is no jump to catch.
Transactionality is needed primarily to maintain data consistency, i.e. when one data structure is written by several methods to several tables and it is important to make sure that all write operations were completed successfully, otherwise the data will be inconsistent.
In your case, it is not very clear why transactionality is implemented.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question