【问题标题】:How to display children from childrens table in parents' Index page?如何在父母的索引页面中显示孩子表中的孩子?
【发布时间】:2020-09-06 11:53:53
【问题描述】:

我有一个具有“bank_name”、“account_name”和“balance”字段的银行模型。另一个模型交易是用户首先选择银行并输入opening_balance和transaction_amount,而closeing_balance是“期初余额+- transaction_amount”(-,+取决于借方/贷方)成为银行模型中的“余额”。我想通过从 transactions 表中获取 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>

【问题讨论】:

    标签: php laravel eloquent model controller


    【解决方案1】:

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

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

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

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

    【讨论】:

    • transaction() 是一个简单的关系,所以你可以给它添加作用域:latest() , orderBy("something") ......等等
    • 如果我添加你的两个 cmets 那么这就是我需要的答案。返回 $this->hasOne('App\Transaction')->latest();非常感激。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多