Using database transactions in Laravel and catching exceptions after transaction failure

高洛峰
Release: 2023-03-05 15:34:02
Original
2257 people have browsed it

Description

In Laravel, if you want to run a set of operations in a database transaction, 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 reverting 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
Copy after login

Manual operation of transactions

If you want to manually handle the transaction and have full control over the restore or commit operation , you can use the beginTransaction method in the DB facade:

DB::beginTransaction();
Copy after login
Copy after login

You can also use the rollBack method to restore the transaction:

DB::rollBack();
Copy after login
Copy after login

Finally, you can submit the transaction through the commit method :

DB::commit();
Copy after login
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

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 are many-to-many. relationship, then three tables are needed to implement this data structure:

Knowledge point table wiki:

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

Test point table tag:

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

Test point knowledge point association table wiki_tag_rel

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

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

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

<?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('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']);
     }

}
Copy after login
Copy after login

                                                                  

Description

In Laravel, if you want to run a set of operations in a database transaction, 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 reverting 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
Copy after login

Manual operation of transactions

If you want to manually handle the transaction and have full control over the restore or commit operation , you can use the beginTransaction method in the DB facade:

DB::beginTransaction();
Copy after login
Copy after login

You can also use the rollBack method to restore the transaction:

DB::rollBack();
Copy after login
Copy after login

Finally, you can submit the transaction through the commit method :

DB::commit();
Copy after login
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

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 are many-to-many. relationship, then three tables are needed to implement this data structure:

Knowledge point table wiki:

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

Test point table tag:

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

Test point knowledge point association table wiki_tag_rel

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

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

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

<?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('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']);
     }

}
Copy after login
Copy after login

For more articles related to using database transactions in Laravel and capturing exceptions after transaction failures, please pay attention to 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!