我有模型Member
,Loan
和Interestamount
。Loan
与Interestamount
具有hasMany
的关系。我似乎无法从Interestamount
访问数据。
我可以在刀片中显示贷款id
和Interestamount
,但不能为给定的Loan
整理Interestamount
。
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 IlluminateDatabaseEloquentModel;
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');
}
}
iSPERYAMONT.PHP
use IlluminateDatabaseEloquentModel;
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>
$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
将您的贷款兴趣更改为此
<td>{{$loanData->member->name}}</td>
@foreach($loanData->interestamount as $int)
<td>{{$int->interestamount}} </td>
@endforeach
</tr>
当我们使用$loanData->interestamount()
时,它是指查询构建器,但是当我们使用$loanData->interestamount
时,它将返回与$loanData->interestamount()->get()
我不知道原因,但是我这样做了。
<td>{{$loanData->member->name}}</td>
@foreach($loanData->interestamount()->get() as $int)
<td>{{$int->interestamount}} </td>
@endforeach