使用PHP的MongoDB 4.0中的事务示例 [英] Example of a transaction in MongoDB 4.0 using PHP

查看:489
本文介绍了使用PHP的MongoDB 4.0中的事务示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在PHP中使用mongoDB展示一个事务.在我的示例中,我有帐户"和转帐".我的第一个操作是从发件人帐户"中扣除余额,然后尝试将资金转入受益人帐户",但是后者不能接受任何转帐,因此,交易应回滚,即应将钱退还给发件人帐户.

I need to showcase a transaction using mongoDB in PHP. In my example, I have "accounts" and "transfers". The first operation I am deducting balance from the "sender account" and attempt to send the money to "beneficiary account", but the latter cannot accept any transfers therefore, the transction should rollback i.e. the money should be returned on senders account.

我找不到有关在线交易的任何PHP具体文档,因此我真的不知道该怎么做.

I could not find any PHP specific documentation regarding transactions online and thus I do not really know how to go about it.

谢谢您的帮助!

推荐答案

如果您使用的是包装驱动程序的PHP库,请在创建Client实例后,例如名为$client,您可以执行以下操作:

If you're using the PHP library that wraps the driver, after creating an instance of Client e.g. called $client, you can do the following:

$session = $client->startSession();
$session->startTransaction();
try {
    // Perform actions.
    $session->commitTransaction();
} catch(Exception $e) {
    $session->abortTransaction();
}

很遗憾,我在 PHP库参考中找不到任何相关文档经过粗略的搜索,但我在 PHP库的问题中找到了示例建议从客户端创建一个会话,然后使用该会话开始然后提交或中止事务,这是适当的过程.

Unfortunately I couldn't find any relevant documentation in the PHP library reference after a cursory search, but I found examples in the PHP library's issues that suggest that creating a session from the client and using that session to start then either commit or abort the transaction is the appropriate procedure.

但是,有几件事要注意:

A couple of things to be aware of, however:

  • $ session变量需要在单独的参数中传递. IE.如果要在会话中执行insertOne(['abc' => 1]),则需要insertOne(['abc' => 1], ['session' => $session]).如果您不这样做,那么该操作仍将执行,但不会成为会话的一部分-即,如果您稍后回滚该会话,它们将不会被撤消.

  • The $session variable needs to be passed in in a separate parameter. I.e. if you want to execute insertOne(['abc' => 1]) in a session, you'll need insertOne(['abc' => 1], ['session' => $session]). If you don't do this the operations will still be executed, but won't be part of the session - i.e. if you later roll the session back, they won't be undone.

如果配置了副本集.在此阶段,MongoDB不支持独立服务器上的事务.

Transactions are only available if you have configured a replica set. At this stage MongoDB does not support transactions on a standalone server.

如果查看MongoDB文档(如上链接),您会注意到对使用副本集的要求并未特别突出地显示在第三个标题下,并且位于所有示例代码之后(如果您像我一样,这将是您首先要寻找的东西.)

If you view the MongoDB docs (as linked above) you'll note that the requirement for a replica set to be in use is not particularly prominently displayed, being in under the third heading, and coming after all of the example code (which, if you're anything like me, will be the first thing you look for).

这篇关于使用PHP的MongoDB 4.0中的事务示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆