计算会员忠诚计划的剩余积分、到期积分

问题描述 投票:0回答:1

我的数据库中有这样的数据

哪里 id = 交易ID type = 交易类型(EARN = 用户从商店获取积分,REDEEM = 用户使用积分) expiredAt = 积分到期时间(赚取积分还有 1 年到期时间)

我的问题是我需要计算

  1. 用户剩余积分。例如。如果我在这一天(2024年2月19日)查询还剩多少分。 (过期积分不计算)
  2. 到期点(本月)

这是我的 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;
    }

php laravel
1个回答
0
投票

解决方案可能比您想象的要容易得多。

考虑到

points
可能是负数或正数,具体取决于类型字段。像这样简单地运行一个数据库查询怎么样:

SELECT memberId, SUM(points) AS points_remaining
FROM your_table
WHERE expiredAt IS NULL
GROUP BY memberId
© www.soinside.com 2019 - 2024. All rights reserved.