数据库事务在laravel 5.2中不起作用?

时间:2022-10-18 17:38:24

My db transaction having so many insert queries,

我的db事务具有如此多的插入查询,

DB::transaction(function() use ($visaForms, $fields) {
            foreach ($visaForms as $visaForm) {
                $visaForm->save();
                foreach ($fields as $field) {
                    $field->visaForm()->associate($visaForm);
                    $field->save();
                    $field->details()->saveMany($field->getDetails());
                    !empty($field->getOptions()) ? $field->options()->saveMany($field->getOptions()) : NULL;
                    !empty($field->getRules()) ? $field->rules()->attach($field->getRules()) : NULL;
                }
            }
        });

When Integrity constraint violation throws by attach() function, Complete transactions are not rolling back. partial insertion will happening there. What is wrong with my code?

当attach()函数抛出Integrity约束违规时,Complete事务不会回滚。部分插入将在那里发生。我的代码出了什么问题?

1 个解决方案

#1


1  

Check here if your database engine supports transactions. I usually use transactions this way:

检查数据库引擎是否支持事务。我通常以这种方式使用交易:

DB::beginTransaction();
try {
    //Code (DB insertions, ...)
    DB::commit();
} catch(Exception $e) {
    DB::rollback();
    //Handle error
}

#1


1  

Check here if your database engine supports transactions. I usually use transactions this way:

检查数据库引擎是否支持事务。我通常以这种方式使用交易:

DB::beginTransaction();
try {
    //Code (DB insertions, ...)
    DB::commit();
} catch(Exception $e) {
    DB::rollback();
    //Handle error
}