我的数据库中有这样的数据
哪里 id = 交易ID type = 交易类型(EARN = 用户从商店获取积分,REDEEM = 用户使用积分) expiredAt = 积分到期时间(赚取积分还有 1 年到期时间)
我的问题是我需要计算
这是我的 php 函数
public function calculateRemainingPoints($memberId)
{
// Fetch all transactions for the memberId
$transactions = Transaction::where('memberId', $memberId)->orderBy('created_at')->get();
// Initialize total points
$totalPoints = 0;
// Process each transaction
foreach ($transactions as $transaction) {
if ($transaction->type == 'EARN') {
// Check if the EARN points are not expired
$expiredAt = Carbon::parse($transaction->expiredAt);
$currentDate = Carbon::now();
if ($expiredAt->gt($currentDate)) {
// Accumulate EARN points
$totalPoints += $transaction->points;
}
} elseif ($transaction->type == 'REDEEM') {
// Deduct REDEEM points
$totalPoints -= $transaction->points;
}
}
return $totalPoints;
}
解决方案可能比您想象的要容易得多。
考虑到
points
可能是负数或正数,具体取决于类型字段。像这样简单地运行一个数据库查询怎么样:
SELECT memberId, SUM(points) AS points_remaining
FROM your_table
WHERE expiredAt IS NULL
GROUP BY memberId