0

I have Bank table and transaction table. The relationship is one-to-many, so a bank may have many transactions. Transaction table has the bank foreign key(bank_id). and each transaction has a column 'type' which is either credit or debit. I want to show each bank balance based on its transactions.

Here are my questions:

  1. How to select a specific bank?
  2. How to calculate the balance for a bank?
  3. Should I calculate it in controller, model, or view? which one is the best?

Here is transactions table: enter image description here thanks in advance!

Mahdi Jafari
  • 347
  • 6
  • 22

3 Answers3

1

You need to create relationships in the model, like this in the Transactions model:

public function bank(){
 return $this->belongsTo(Bank::class);
}

and this in the Bank Model

public function transactions (){
 return $this->hasMany(Transactions::class);
}

Then you can access them like this:

$this->bank->transactions;

Laravel has excellent docs, you just need to read them, e.g. Relationships

damask
  • 529
  • 4
  • 17
  • thanks @damask for your quick response. I have done the relationship between bank and transaction. but now I got stuck that how to choose a specific bank and then show it's balance. can you help with that? – Mahdi Jafari Apr 06 '21 at 07:11
  • thanks @damask! I got the idea from your code and the problem solved. – Mahdi Jafari Apr 06 '21 at 09:25
  • @MahdiJafari You should accept an Answer, or explain how you solved your problem to help others. – damask Apr 06 '21 at 23:16
1

I'm not sure what you are trying to do. You'd select a bank like

$bank = Bank::find(2);

and you could do something like

$bank->transactions->sum('amount');
damask
  • 529
  • 4
  • 17
  • Yeah. I wanted to show the balance of each bank in my database. I had to sum all credits which belongs to a bank and then sum all debits for that bank and then find the balance, which is credits minus debits. So using relationship you mentioned. I wrote this code. {{$bank->transactions->where('type', 'credit')->sum('amount') - $bank->transactions->where('type', 'debit')->sum('amount')}} – Mahdi Jafari Apr 07 '21 at 03:44
0

I wanted to show the balance of each bank in my database. I had to sum all credits which belongs to a bank and then sum all debits for that bank and then find the balance, which is credits minus debits. So using relationship you mentioned. I wrote this code.

<td>{{$bank->transactions->where('type', 'credit')->sum('amount') - $bank->transactions->where('type', 'debit')->sum('amount')}}</td>
Mahdi Jafari
  • 347
  • 6
  • 22