Home>Article>PHP Framework> Transaction operations in ThinkPHP5

Transaction operations in ThinkPHP5

silencement
silencement forward
2020-01-30 22:49:41 4628browse

Transaction operations in ThinkPHP5

If you use transaction processing, the database engine needs to support transaction processing. For example, MySQL's MyISAM does not support transaction processing and requires the use of the InnoDB engine.

ThinkPHP5.0

Use the transaction method to operate database transactions. When an exception occurs, it will automatically roll back, for example:

Automatically control transactions Handling

Db::transaction(function(){ Db::table('think_user')->find(1); Db::table('think_user')->delete(1);});

You can also manually control transactions, for example:

// 启动事务Db::startTrans();try{ Db::table('think_user')->find(1); Db::table('think_user')->delete(1); // 提交事务 Db::commit(); } catch (\Exception $e) { // 回滚事务 Db::rollback();}

ThinkPHP5.1

The simplest way is to use the transaction method to operate database transactions. When the code in the closure An exception will be automatically rolled back, for example:

Db::transaction(function () { Db::table('think_user')->find(1); Db::table('think_user')->delete(1);});

You can also manually control the transaction, for example:

// 启动事务Db::startTrans();try { Db::table('think_user')->find(1); Db::table('think_user')->delete(1); // 提交事务 Db::commit();} catch (\Exception $e) { // 回滚事务 Db::rollback();}

Note that during transaction operations, make sure that your database connection is using the same one.

Starting from version V5.1.13, MySQL’s XA transaction can be supported to implement global (distributed) transactions. You can use:

Db::transactionXa(function () { Db::connect('db1')->table('think_user')->delete(1); Db::connect('db2')->table('think_user')->delete(1);}, [Db::connect('db1'),Db::connect('db2')]);

Make sure your data table engine is InnoDB, and Enable XA transaction support.

The above is the detailed content of Transaction operations in ThinkPHP5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:www.liqingbo.cn. If there is any infringement, please contact admin@php.cn delete