数据库事务
🌐 Database transactions
Page summary:
数据库事务将多个操作组合在一起,使它们作为一个整体成功或回滚。实验性的
strapi.db.transaction辅助工具提供trx、提交和回滚功能,用于封装的服务调用。
这是一个实验性功能,可能会在未来版本中发生变化。
🌐 This is an experimental feature and is subject to change in future versions.
Strapi 5 提供一个 API 来将一组操作封装在一个事务中,以确保数据的完整性。
🌐 Strapi 5 provide an API to wrap a set of operations in a transaction that ensures the integrity of data.
事务是一组作为单一单元一起执行的操作。如果其中任何操作失败,整个事务将失败,数据会回滚到之前的状态。如果所有操作都成功,事务将提交,数据将永久保存到数据库中。
🌐 Transactions are a set of operations that are executed together as a single unit. If any of the operations fail, the entire transaction fails and the data is rolled back to its previous state. If all operations succeed, the transaction is committed and the data is permanently saved to the database.
使用
🌐 Usage
事务通过将处理函数传入 strapi.db.transaction 来处理:
🌐 Transactions are handled by passing a handler function into strapi.db.transaction:
await strapi.db.transaction(async ({ trx, rollback, commit, onCommit, onRollback }) => {
// It will implicitly use the transaction
await strapi.entityService.create();
await strapi.entityService.create();
});
在事务处理程序执行后,如果所有操作都成功,则事务会被提交。如果任何操作抛出异常,事务将被回滚,数据会恢复到之前的状态。
🌐 After the transaction handler is executed, the transaction is committed if all operations succeed. If any of the operations throws, the transaction is rolled back and the data is restored to its previous state.
在事务块中执行的每个 strapi.entityService 或 strapi.db.query 操作将隐式使用该事务。
🌐 Every strapi.entityService or strapi.db.query operation performed in a transaction block will implicitly use the transaction.