Transaction Operations (Query Builder 16)


The simplest way is to use the transaction method to operate database transactions. When an exception occurs in the code in the closure, it will automatically roll 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, ensure that your database connection is using the same one.

Can support MySQL's XA transaction 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.