ホームページ >バックエンド開発 >PHPチュートリアル >Laravelでの悲観的なロックでデータレースの管理
Laravelフレームワークは、同時データベース操作におけるデータ競争を効果的に防ぐための強力な悲観的ロックメカニズムを提供します。 sharedLock()
およびlockForUpdate()
メソッドを使用すると、高い並行性シナリオでデータの一貫性を維持できます。
sharedLock()
メソッドは読み取りを許可しますが、修正を防ぎます:
DB::table('users') ->where('votes', '>', 100) ->sharedLock() ->get();
より厳格な制御の場合、lockForUpdate()
メソッドは同時にロックの変更と共有を防ぎます:
DB::table('orders') ->where('status', 'pending') ->lockForUpdate() ->get();
この方法は、金融取引または在庫管理システムで特に重要です。
class PaymentController extends Controller { public function processPayment($orderId, $amount) { return DB::transaction(function () use ($orderId, $amount) { $account = DB::table('accounts') ->where('order_id', $orderId) ->lockForUpdate() ->first(); if ($account->balance >= $amount) { DB::table('accounts') ->where('order_id', $orderId) ->update(['balance' => $account->balance - $amount]); return ['success' => true, 'message' => 'Payment processed successfully']; } return ['success' => false, 'message' => 'Insufficient funds']; }); } }データの正確性を確保する必要があるアプリケーションでは、複数のプロセスが同じデータを同時に変更しようとする場合があり、これらのロックメカニズムが重要です。
以上がLaravelでの悲観的なロックでデータレースの管理の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。