Detailed explanation of how Laravel uses database transactions and exception handling

*文
Release: 2023-03-19 08:52:01
Original
2417 people have browsed it

I have been learning Laravel recently and encountered a lot of problems while learning, so I wanted to summarize and record it. So the following article mainly introduces you to the relevant information about how Laravel uses database transactions and captures exceptions after transaction failures. , friends in need can refer to it, let’s take a look below.

Preface

If you want to run a set of operations in a database transaction in Laravel, you can use the transaction method in the DB facade . If an exception is thrown within a transaction's closure, the transaction will be automatically restored. If the closure runs successfully, the transaction will be automatically committed.

You don’t need to worry about manually restoring or committing the transaction when using the transaction method:

DB::transaction(function () {
 DB::table('users')->update(['votes' => 1]);

 DB::table('posts')->delete();
});
Copy after login

Manually operate the transaction

If you want To handle transactions manually and have full control over restore or commit operations, you can use the beginTransaction method on the DB facade:

DB::beginTransaction();
Copy after login

You can also restore transactions through the rollBack method:

DB::rollBack();
Copy after login

Finally, you can pass commit method to commit this transaction:

DB::commit();
Copy after login

Note: The transaction method of the DB facade can also be used to control the query statement builder and Eloquent ORM transactions.

Example introduction

# Suppose you want to store a knowledge point in the database. This knowledge point belongs to two different test points at the same time. , that is, the two data of test points and knowledge points have a many-to-many relationship, so to implement this data structure, three tables are needed:

Knowledge point table wiki:

---------------------------------------
id  title    content
---------------------------------------
Copy after login

Test points Table tag:

-------------------
id  name
-------------------
Copy after login

Test point knowledge point association table wiki_tag_rel

----------------------------------
id   tag_id  wiki_id
----------------------------------
Copy after login

Now we need to open the transaction to add Wiki data. After the wiki is successfully added, associate it to the designated test point

(When using the query builder or Eloquent ORM to execute the query in laravel, an Illuminate\Database\QueryException exception will be returned if it fails)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use App\Wiki;

class TestController extends Controller
{
 //用DB facade的事务方法控制 查询语句构建器的事务
 public function storeWiki(Request $request)
 {
  DB::beginTransaction();
  try {
   $tagIds = explode(&#39;,&#39;, $request->get(&#39;tag_id&#39;));
   $wiki_id = DB::table(&#39;wiki&#39;)->insertGetId([
    &#39;title&#39; => $request->get(&#39;title&#39;),
    &#39;content&#39; => $request->get(&#39;content&#39;)
   ]);

   $relationData = [];
   foreach($tagIds as $tagId) {
    $data = [&#39;wiki_id&#39; => $wiki_id, &#39;tag_id&#39; => $tagId];
    $relationData[] = $data;
   }
   DB::table(&#39;wiki_tag_rel&#39;)->insert($relationData);
   DB::commit();
  } catch(\Illuminate\Database\QueryException $ex) {
   DB::rollback();
   return \Response::json([&#39;status&#39; => &#39;error&#39;, &#39;error_msg&#39; => &#39;Failed, please contact supervisor&#39;]);
  }
  
  return \Response::json([&#39;status&#39; => &#39;ok&#39;]);
 }


 //用DB facade的事务方法控制 Eloquent ORM的事务
 public function createWiki(array $data)
 {
  DB::beginTransaction();
  try {
   $tagIds = explode(&#39;,&#39;, $data[&#39;tag_id&#39;]);
   $newWiki = Wiki::create([
    &#39;title&#39; => $data[&#39;title&#39;],
    &#39;content&#39; => $data[&#39;content&#39;]
   ]);
   //Wiki和Tag两个Model使用了belongsToMany建立了多对多的关系
   //通过attach方法来附加wiki和tag的关系(写入中间表)
   $newWiki->tags()->attach($tagIds);
   DB::commit();
  } catch(QueryException $ex) {
   DB::rollback();
   return \Response::json([&#39;status&#39; => &#39;error&#39;, &#39;error_msg&#39; => &#39;Failed, please contact supervisor&#39;]);
  }

  return \Response::json([&#39;status&#39; => &#39;ok&#39;]);
  }

}
Copy after login

Related recommendations:

Detailed explanation of how Laravel modifies .env configuration through the background

Explore how Laravel's middleware is implemented

Laravel Optimization Split Routing File

The above is the detailed content of Detailed explanation of how Laravel uses database transactions and exception handling. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template