Hi everyone.
Let say i have a table of transactions, that has columns ID, Date, Quantity. But for the sake of clarity, i will add "Qty Balance" column to this sample for a better view or understanding.
+----+------------+----------+-------------+
| ID | Date | Quantity | Qty Balance |
+----+------------+----------+-------------+
| 1 | 2023-01-01 | 10 | 10 |
| 2 | 2023-01-01 | 10 | 20 |
| 3 | 2023-01-01 | 10 | 30 |
| 4 | 2023-01-01 | -20 | 10 |
| 5 | 2023-01-01 | 5 | 15 |
| 6 | 2023-01-02 | 5 | 20 |
| 7 | 2023-01-02 | 5 | 25 |
| 8 | 2023-01-02 | 5 | 30 |
| 9 | 2023-01-03 | -30 | 0 |
| 10 | 2023-01-03 | 10 | 10 |
| 11 | 2023-01-03 | 5 | 15 |
| 12 | 2023-01-03 | 5 | 20 |
| 13 | 2023-01-03 | 10 | 30 |
| 14 | 2023-01-04 | 20 | 50 |
| 15 | 2023-01-04 | 10 | 60 |
| 16 | 2023-01-04 | 15 | 75 |
| 17 | 2023-01-04 | -75 | 0 |
| 18 | 2023-01-04 | 5 | 5 |
| 19 | 2023-01-04 | 10 | 15 |
| 20 | 2023-01-05 | -5 | 10 |
+----+------------+----------+-------------+
So, this is a historical of multiple transactions of an item, let say Item X, i've search so many reference to validate the running balance when i am updating a single row (1), or inserting a new row in the middle (2). But what i've found that it always need an iteration to calculate the running balance and if it find a negative value, then just throw an exception.
There is 2 cases of this, but i think it will have the same solutions. The first one is
- Update a row in the middle
- Insert a new or in the middle
It will become a problem if i am updating or inserting a subtraction, if it's an addition then it's fine.
So lets jump to the example, when i am updating a row in the middle, let say i am updating row with an ID of 3, i will update it's quantity from 10 to 4 (it is a subtraction). It will make running balance at ID 9 a negative number, and i need to validate this and throw an error. Data will look like this:
+----+------------+----------+-------------+
| ID | Date | Quantity | Qty Balance |
+----+------------+----------+-------------+
| 1 | 2023-01-01 | 10 | 10 |
| 2 | 2023-01-01 | 10 | 20 |
| 3 | 2023-01-01 | 4 | 24 |
| 4 | 2023-01-01 | -20 | 4 |
| 5 | 2023-01-01 | 5 | 9 |
| 6 | 2023-01-02 | 5 | 14 |
| 7 | 2023-01-02 | 5 | 19 |
| 8 | 2023-01-02 | 5 | 24 |
| 9 | 2023-01-03 | -30 | -6 |
| 10 | 2023-01-03 | 10 | 4 |
| 11 | 2023-01-03 | 5 | 9 |
| 12 | 2023-01-03 | 5 | 14 |
| 13 | 2023-01-03 | 10 | 24 |
| 14 | 2023-01-04 | 20 | 44 |
| 15 | 2023-01-04 | 10 | 54 |
| 16 | 2023-01-04 | 15 | 69 |
| 17 | 2023-01-04 | -75 | -6 |
| 18 | 2023-01-04 | 5 | -1 |
| 19 | 2023-01-04 | 10 | 9 |
| 20 | 2023-01-05 | -5 | 4 |
+----+------------+----------+-------------+
How do i achive this using raw or eloquent methods ? Thank you
Edit:
"Qty Balance" is not an existing column, it's just an example to easily understand the calculation.