A
A
Artyom2015-08-19 20:27:48
Yii
Artyom, 2015-08-19 20:27:48

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

2 answer(s)
A
Andrey Klyuev, 2015-08-20
@BBird

This is

$transaction->rollBack();
    foreach ($this->firstErrors as $key => $value) break;
    if (empty($value)) $value = 'Неизвестная ошибка';
    return array('message' => $value, 'status' => false);

replace with something like this
And already in catch'a you do your checks and generate error messages, if necessary.
And everything should work.

P
Paulus, 2015-08-20
@ppokrovsky

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 question

Ask a Question

731 491 924 answers to any question