Rollback problems on Laravel 5.5

Asked

Viewed 124 times

1

I am importing/migrating an old database from my site to a new format. I am using Transactions in this import as per the code below.

The problem is that when I get an error the rollback is not being fired. For example I have 5 records that will be included in a batch within begintransaction and have an error in record 3. The exception is generated treated but when I look in the bank the 3 records were included even with the error.

What I’m doing wrong. Thank you

$erros = new Erros();
\DB::beginTransaction();
try {         
        $pesq = $original->whereIn('cod', $request->get('codigo'))->get();            
        foreach ($pesq as $valores) {                
            $temp = [
                'id' => $valores->codigo,
                'plano_id' => 0,                    
                'cliques' => $valores->qtd_cliques,                    
                'caracteristicas' => $valores->caracteristicas,                    
                'destaque' => ($valores->destaque == 0) ? 1 : 0,
                'imagem' => $valores->imagemDestaque,                    
                'created_at' => $valores->created_at,
                'updated_at' => $valores->updated_at,
                'deleted_at' => $valores->deleted_at,
            ];

            \DB::table('casas')->insert($temp);                

            if(strlen($valores->filme)>2){
                throw new \Exception('Este imóvel contém 1 video que deve ser incluído manualmente.');
            }
        }
        \DB::commit();
} catch (\Exception $e) {
        \DB::rollback();
        $erros->setId($valores->codigo);
        $erros->setCodigo($e->getCode());
        $erros->setMensagem($e->getMessage());
}

2 answers

0

To capture the exceptions generated by the bank use \PDOException, to \Exception does not capture this type of error. Possibly as the error is not being captured the transaction occurs normalmente.

Within your if an exception is also being generated, thus interrupting the code execution flow, put a DB::rollback() in that stretch also.

  • good morning. Look I did it and it’s still not working. The error is being captured being dealt with in the lines below the rollback and displayed in the right view. But the rollback does not do his job. I am forcing duplicate key error in the database as an example. It capitals and displays this error formatted on the right screen. SQLSTATE[23000]: Integrity Constraint Violation: 1062 Duplicate entry.

0


After trying a lot together with Dinaerte Neto of the Laravel Brasil Facebook group, we verified that the problem was that the table was of the Myisam type and it seems that it does not support transactions. I switched to INODB and all right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.