S
S
SvizzZzy2018-06-12 17:57:33
Laravel
SvizzZzy, 2018-06-12 17:57:33

How to use save model and transactions in laravel 5?

Trying to make transactions for multiple saves + a few more saves in a foreach loop:

\DB::beginTransaction();
          try {
 
          $blabla1 = new Test1;
          $blabla1->blabla= 123;
          $blabla1->save();

          $rows = Test2::where('field', 'test')->get();
 
          foreach ($rows as $row) {
            $row->blabla111= 0; //специально допускаю ошибку (несущ.поле таблицы)
            $row->save();
          }

          \DB::commit(); 

          } catch (\Exception $e) { 
              \DB::rollBack();
          }

The problem is that \DB::rollBack(); doesn't work at all, blabla1 saves 123, but blabla111 of course doesn't (Exception is triggered)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SvizzZzy, 2018-06-12
@SvizzZzy

It turned out that in my case it was necessary to explicitly specify the name of the connection to the database. And everything worked fine.
ps: rollBack(); - not useful because probably if $cn->commit(); fails, all requests are cancelled.
My code:

$cn = DB::connection('ИМЯ_подкл_к_базе'); //DB_CONNECTION из ENV
$cn->beginTransaction();
  try{

  //Мои запросы типа Model::where, save() и тд...
  ...
  
  $cn->commit();

} catch(\Exception $e){

  return 'error';

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question