简体   繁体   English

使用雄辩的ORM执行MYSQL事务

[英]Using Eloquent ORM to perform MYSQL transactions

A few weeks back I had an interesting inquiry regarding the handling/processing of an inventory/payment system and I've decided to implement the method of the accepted answer being it was both the most simplistic and more likely the most efficient solution given. 几周前,我对库存/付款系统的处理/处理提出了一个有趣的询问 ,我决定实施公认的方法,因为它既是最简单的解决方案,也可能是最有效的解决方案。

I'm using Laravel's Eloquent ORM in conjunction with the Slim Framework , and I'd like to perform a MYSQL transaction with a specific query regarding the decrementation of the stock of items within an inventory system. 我将Laravel的Eloquent ORMSlim Framework结合使用,我想执行一个MYSQL transaction ,并执行一个特定查询,该查询涉及库存系统中物品存量的减少。 The code that I'd like to use a transaction for is the following: 我要用于transaction的代码如下:

    // decrement each items stock following successful payment
    try {
      // here is where i'd like to perform a transaction, rather than simple eloquent query
         foreach ($this->c->basket->all() as $product) {
            $product->decrement('stock', $product->quantity);
        }
    } catch (Exception $e) {

        // if error is caused during decremention of item(s),
        // handle accordingly 

    }

Now being that I am using Slim as aforementioned, I believe I don't have native access to the Laravel DB Facade which to my knowledge handles transactions. 现在,如上所述,我正在使用Slim,我相信我没有对Laravel DB Facade的本机访问, 我所知, Laravel DB Facade处理事务。

Suggestions? 建议?

SIDE-NOTE 边注

My DB Connection is set globally in an initialization file like so: 我的数据库连接是在initialization文件中全局设置的,如下所示:

$capsule = new Illuminate\Database\Capsule\Manager();

$capsule->addConnection($container['settings']['db']);

$capsule->setAsGlobal();

$capsule->bootEloquent();

You could get the Capsule object from the slim container and then just use the Connection object to start and commit a database transaction. 您可以从slim容器中获取Capsule对象,然后仅使用Connection对象启动并提交数据库事务。 If an exception occurs you just need to call the rollBack() method. 如果发生异常, rollBack()需要调用rollBack()方法即可。

Pseudo code: 伪代码:

$capsule = new \Illuminate\Database\Capsule\Manager();

// Get a registered connection instance.
$connection = $capsule->getConnection();

// begin a transaction manually
$connection->beginTransaction();

try {
    // do something...
    $product->decrement('stock', $product->quantity);

    // commit a transaction via the commit method
    $connection->commit();
} catch (Exception $e) {
    // you can rollback the transaction via the rollBack method
    $connection->rollBack();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM