如何在 parents' 索引页中显示 childrens table 中的 children?

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

我有一个 Bank 模型,它有 'bank_name'、'account_name' 和 'balance' 字段。另一种模型交易是用户首先选择银行并输入 opening_balance 和 transaction_amount 以及 closing_balance 即“期初余额 +- transaction_amount”(-,+ 取决于 debit/credit) 在银行模型中变成“余额”。我想通过从交易 table 中获取 closing_balance 来在 bank.index 页面中显示特定银行的余额。我被困在这里。到目前为止我有:

银行型号:

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

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

交易模型:

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

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

银行控制器:

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')); 
}

事务控制器:

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

Bank.index 页

<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>

您可以在 Bank 模型 中定义另一个关系,它给您一个模型对象而不是像这样的数组:

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

然后您可以在 bank.index 视图中使用此关系:

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