Answer the question
In order to leave comments, you need to log in
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();
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question