首页 > 解决方案 > 访问具有一对多关系的子属性

问题描述

我有模型MemberLoanInterestamountLoanhasMany关系Interestamount。我似乎无法从Interestamount.

我可以显示贷款idInterestamount刀片,但不能Interestamount为给定的Loan

贷款控制器.php

public function loanInterest($criteria){
    //$loanData = Loan::all();
    $loanData =Loan::findOrFail($criteria);
    return view($this->_pagePath.'loan.loaninterest',compact('loanData'));
}

网页.php

Route::any('loaninterest/{criteria?}','LoanController@loanInterest')
    ->name('loaninterest');

贷款.php

use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
    protected $fillable = [
        'amount',
        'interest',
        'status',
        'duration',
        'member_id',
        'loan_type_id',
        'interest_type_id',
        'loan_payment_type_id'
    ];

    // protected $appends = 'interest_amount

    public function getInterestAmountAttribute()
    {
        return ($this->amount)/100 * $this->interest;
    }

    public function interestamount()
    {
        return $this->hasMany(InterestAmount::class,'loan_id','id');
    }
}

利息金额.php

use Illuminate\Database\Eloquent\Model;
class InterestAmount extends Model
{
    protected $fillable = ['interestamount'];

    public function loan()
    {
        return $this->belongsTo(Loan::class,'loan_id','id');
    }
}

贷款利息.blade.php

<tr>
    <td>{{$loanData->member->name}}</td>
    @foreach($loanData->interestamount() as $int)
        <td>{{$int->interestamount}} </td>
    @endforeach     
</tr>

贷款刀片.php

<a href="{{route('loaninterest', $loan->id) }}">Interest detail</a>

标签: laraveleloquenthas-many

解决方案


将您的贷款利息更改为此

<td>{{$loanData->member->name}}</td>
  @foreach($loanData->interestamount as $int)
   <td>{{$int->interestamount}} </td>
  @endforeach     
</tr>

当我们使用$loanData->interestamount()它时,它指的是一个查询构建器,但是当我们使用它时,$loanData->interestamount它返回的相关集合与$loanData->interestamount()->get()


推荐阅读