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(); });
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();
You can also restore transactions through the rollBack method:
DB::rollBack();
Finally, you can pass commit method to commit this transaction:
DB::commit();
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 ---------------------------------------
Test points Table tag:
------------------- id name -------------------
Test point knowledge point association table wiki_tag_rel
---------------------------------- id tag_id wiki_id ----------------------------------
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)
get('tag_id')); $wiki_id = DB::table('wiki')->insertGetId([ 'title' => $request->get('title'), 'content' => $request->get('content') ]); $relationData = []; foreach($tagIds as $tagId) { $data = ['wiki_id' => $wiki_id, 'tag_id' => $tagId]; $relationData[] = $data; } DB::table('wiki_tag_rel')->insert($relationData); DB::commit(); } catch(\Illuminate\Database\QueryException $ex) { DB::rollback(); return \Response::json(['status' => 'error', 'error_msg' => 'Failed, please contact supervisor']); } return \Response::json(['status' => 'ok']); } //用DB facade的事务方法控制 Eloquent ORM的事务 public function createWiki(array $data) { DB::beginTransaction(); try { $tagIds = explode(',', $data['tag_id']); $newWiki = Wiki::create([ 'title' => $data['title'], 'content' => $data['content'] ]); //Wiki和Tag两个Model使用了belongsToMany建立了多对多的关系 //通过attach方法来附加wiki和tag的关系(写入中间表) $newWiki->tags()->attach($tagIds); DB::commit(); } catch(QueryException $ex) { DB::rollback(); return \Response::json(['status' => 'error', 'error_msg' => 'Failed, please contact supervisor']); } return \Response::json(['status' => 'ok']); } }
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!