简体   繁体   中英

How to display children from childrens table in parents' Index page?

I have a Bank model which has 'bank_name', 'account_name' and 'balance' fields. Another model Transaction is where user first selects the bank and inputs opening_balance and transaction_amount and the closing_balance which is "opening balance +- transaction_amount" (-, + depending upon debit/credit) becomes "balance" in Bank Model. I want to show the balance in a particular bank in bank.index page by grabbing the closing_balance from transactions table. I am stuck here. So far I have:

Bank Model:

protected $fillable=['bank_name','account_name'];

public function transactions()
{
    return $this->hasMany('App\Transaction');
}

Transaction Model:

protected $fillable = ['bank_id','opening_balance','transaction_amount','isdebit','closing_balance'];

public function bank()
{
    return $this->belongsTo('App\Bank');
}

BankController:

public function index() 
{ $banks = Bank::all(); 
//$bal_1 = Bank::find(1)->transactions()->latest()->first(); 
// I can show the balance in bank which has id 1 by this manually.
 return view('bank.index', compact('banks','bal_1')); 
}

Transaction Controller:

public function index() 
{ $transactions = Transaction::all(); 
return view('transaction.index',compact('transactions')); 
}

Bank.index page

<table class="table">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Bank Name</th>
        <th scope="col">Account Name</th>
        <th scope="col">Balance</th>
      </tr>
    </thead>
    <tbody>
    @foreach($banks as $i=>$bank)
      <tr>
        <th scope="row">{{++$i}}</th>
        <td>{{$bank->bank_name}}</td>
        <td>{{$bank->account_name}}</td>
        <td>{{$bal_1->closing_balance}}</td>
      </tr>
     @endforeach
    </tbody>
  </table>

You can define another relation in Bank model which give you one model object instead of array like this :

public function transaction()
{
  return $this->hasOne('App\Transaction');
}

Then You can use this relation in your bank.index view :

<td>{{$bank->transaction->closing_balance}}</td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM