Status message

Maintenant, vous regardez: Transactions with eloquent in laravel

Transactions with eloquent in laravel

You may use the transaction method on the DB facade to run a set of operations within a database transaction. If an exception is thrown within the transaction Closure, the transaction will automatically be rolled back. If the Closure executes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the transaction method:

  1. use Illuminate\Support\Facades\DB;
  2.  
  3. DB::transaction(function () {
  4. DB::table('users')->update(['votes' => 1]);
  5.  
  6. DB::table('posts')->delete();
  7. });

The transaction method accepts an optional second argument which defines the number of times a transaction should be reattempted when a deadlock occurs. Once these attempts have been exhausted, an exception will be thrown:

  1. DB::transaction(function () {
  2. DB::table('users')->update(['votes' => 1]);
  3.  
  4. DB::table('posts')->delete();
  5. }, 5);

If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the beginTransaction method on the DB facade:

  1. try {
  2. // DB::transaction(function() {
  3. DB::beginTransaction();
  4.  
  5. $db_data = Candidate::create([
  6. 'name' => $name,
  7. 'gender' => $gender,
  8. 'age' => $age,
  9. 'birth' => $birth,
  10. 'mobile' => $mobile,
  11. 'email' => $email,
  12. 'education' => $education,
  13. 'now_location' => $now_location,
  14. 'service_year' => $service_year,
  15. 'language' => $language
  16. ]);
  17.  
  18. $db_data->resume()->create([
  19. //'candidate_id' => $candidate_id,
  20. 'forward_location' => $forward_location,
  21. 'last_title' => $last_title,
  22. 'owner_id' => $owner_id,
  23. 'uploader_id' => $uploader_id,
  24. 'status' => $status,
  25. 'source' => $source,
  26. 'is_valid' => $is_valid,
  27. 'is_unique' => $is_unique,
  28. 'valid_unique' => $valid_unique,
  29. 'en_cv_flag' => $en_cv_flag,
  30. 'career_objective' => $career_objective,
  31. 'self_evaluations' => $self_evaluations,
  32. 'works_info' => $works_info,
  33. 'projects_info' => $projects_info,
  34. 'education_info' => $education_info,
  35. 'comprehensive_skills' => $comprehensive_skills,
  36. 'original_cv_attach' => $this->public_uri,
  37. 'ori_to_pdf_url' => $ori_to_pdf_url,
  38. 'en_cv_attach' => $en_cv_attach
  39. ]);
  40.  
  41. DB::commit();
  42.  
  43. } catch (\Exception $e) {
  44. DB::rollback();
  45. Event::dispatch(new ParseFilesEvent($this->current_user_id , $name . ' 的简历解析或者入库产生错误,已回滚到最初状态', 1));
  46. }