Here is the actual case, there's two models
- Accounts (id, balance)
- TransactionEntries (id, account_id, amount)
Everytime an transaction entry is updated, account balance will change accordingly to reflect the correct balance, there's a case where I will need to delete some transaction entries and create some transaction entries within one database transaction:
// Database Tx
$tx = (new TxManager())->get();
// Transaction entry to delete
$delTransaction = TransactionEntries::findFirst(1);
$delTransaction->setTransaction($tx);
$delTransaction->account->balance -= $delTransaction->amount; // Amount = 30, Balance = 30
// Balance = 0 now, but not committed to database
if ($delTransaction->delete() == false) {
//THROW EXCEPTION
}
// New transaction
$newTransaction = new TransactionEntries();
$newTransaction->setTransaction($tx);
$newTransaction->account_id = 1; // Same account as previous transaction entry.
$newTransaction->amount = 50;
if ($newTransaction->create() == false) {
// THROW
}
// Update account
$account = Accounts::findFirst(1);
$account->balance += 50; // PROBLEM HERE: account balance is the original 30, not the latest which is 0.
// Account balance = 80 which is wrong, should be 50
if ($account->update() == false) {
// THROW
}
$tx->commit();
I cant think of any easy way to overcome this hurdle.