代码提交

This commit is contained in:
wong
2025-09-30 10:36:51 +08:00
parent ff7b583f07
commit 5313bc6a18
4 changed files with 70 additions and 28 deletions

View File

@@ -2,6 +2,7 @@
namespace app\chukebao\controller;
use app\chukebao\model\TokensCompany;
use app\chukebao\model\TokensRecord;
use library\ResponseHelper;
use think\Db;
@@ -107,12 +108,7 @@ class TokensRecordController extends BaseController
Db::startTrans();
try {
// 使用悲观锁获取用户当前tokens余额确保并发安全
$userInfo = Db::name('users')
->where('id', $userId)
->where('companyId', $companyId)
->lock(true) // 悲观锁,防止并发问题
->find();
$userInfo = TokensCompany::where('companyId', $companyId)->lock(true)->find();
if (!$userInfo) {
throw new \Exception('用户不存在');
}
@@ -123,10 +119,8 @@ class TokensRecordController extends BaseController
$newBalance = $type == 1 ? ($currentTokens + $tokens) : ($currentTokens - $tokens);
// 使用原子更新操作,基于当前值进行更新,防止并发覆盖
$updateResult = Db::name('users')
->where('id', $userId)
$updateResult = TokensCompany::where('companyId', $companyId)
->where('companyId', $companyId)
->where('tokens', $currentTokens) // 确保基于当前值更新
->update([
'tokens' => $newBalance,
'updateTime' => time()