以一对多关系访问子级属性

时间:2019-05-02 06:05:03

标签: laravel eloquent has-many

我有模型MemberLoanInterestamountLoanhasManyInterestamount关系。我似乎无法从Interestamount访问数据。

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

LoanController.php

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

web.php

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

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

InterestAmount.php

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

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

loaninterest.blade.php

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

loan.blade.php

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

3 个答案:

答案 0 :(得分:1)

将您的贷款利息更改为此

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

当我们使用$loanData->interestamount()时,它是指查询生成器,但是当我们使用$loanData->interestamount时,它会返回与$loanData->interestamount()->get()相同的相关集合

答案 1 :(得分:1)

$loanData->interestamount()返回查询构建器实例,而不是查询结果。

有几种方法可以从关系函数获取结果。

其中之一是调用get()函数

Exmaple

$loanData->interestamount()->get();

另一种方法是调用关系函数not as a function but as a property

示例

$loanData->interestamount;

因此在您的刀片文件@foreach()

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

答案 2 :(得分:0)

我不知道原因,但是我做到了,而且奏效了。

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