[英]Using Eloquent ORM to perform MYSQL transactions
幾周前,我對庫存/付款系統的處理/處理提出了一個有趣的詢問 ,我決定實施公認的方法,因為它既是最簡單的解決方案,也可能是最有效的解決方案。
我將Laravel的Eloquent ORM與Slim Framework結合使用,我想執行一個MYSQL transaction
,並執行一個特定查詢,該查詢涉及庫存系統中物品存量的減少。 我要用於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
}
現在,如上所述,我正在使用Slim,我相信我沒有對Laravel DB Facade的本機訪問, 據我所知, Laravel DB Facade處理事務。
建議?
邊注
我的數據庫連接是在initialization
文件中全局設置的,如下所示:
$capsule = new Illuminate\Database\Capsule\Manager();
$capsule->addConnection($container['settings']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
您可以從slim容器中獲取Capsule對象,然后僅使用Connection對象啟動並提交數據庫事務。 如果發生異常, rollBack()
需要調用rollBack()
方法即可。
偽代碼:
$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.