I am trying to figure out what is the best way to do this in Doctrine 2.
I have an Account object that has OneToMany for a transaction object. I need to SUMME all values ββfrom a transaction filtered by account. It's like in SQL: SELECT a.*, SUM(t.amount) AS balance FROM account a INNER JOIN transaction t ON t.account_id = a.id
Method # 1:
Directly on Entity
class Account { // some other definitions /** * @OneToMany(targetEntity="Transaction", mappedBy="account") */ private $transactions; public function getBalance() { $balance = 0; foreach ($this->transactions as $transaction){ $balance += $transaction->getAmount(); } return $balance; } }
I think this is the worst way, since it gets all the related transactions to get their amount.
Method # 2:
Using repositories
class TransactionRepository { public function getBalanceByAccount(Account $account){ $query = $this->em->createQuery("SELECT SUM(t.amount) FROM Transaction t INNER JOIN t.Account a WHERE a.id = ?");
I'm not sure if it will work in a TransactionRepository or AccountRepository.
Method 3:
Using a service template
class TransactionService { public function getBalanceByAccountId($accountId){ $query = $this->em->createQuery("SELECT SUM(t.amount) FROM Transaction t INNER JOIN t.Account a WHERE a.id = ?");
Again, I'm not sure if this is happening in a TransactionService or AccountService.
denormalization of tables, maintaining balance in the accounting / entity table.
Method #n:
Please let me know your suggestion.
source share