laravel - 访问具有一对多关系的子属性
问题描述
我有模型Member
,Loan
和Interestamount
。Loan
有hasMany
关系Interestamount
。我似乎无法从Interestamount
.
我可以显示贷款id
和Interestamount
刀片,但不能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>
解决方案
将您的贷款利息更改为此
<td>{{$loanData->member->name}}</td>
@foreach($loanData->interestamount as $int)
<td>{{$int->interestamount}} </td>
@endforeach
</tr>
当我们使用$loanData->interestamount()
它时,它指的是一个查询构建器,但是当我们使用它时,$loanData->interestamount
它返回的相关集合与$loanData->interestamount()->get()
推荐阅读
- python - 试图在谷歌云中查找已部署 python 函数的当前项目 ID 会出错
- amazon-web-services - 使用 Step Function 在不同的帐户中运行 Glue 作业
- c++ - I cant get the right result from my code, getting odd outputs
- c# - 使用 LINQ 反转和展平字典
- sql - Toad for DB2 On Prem 到 On Cloud - 组执行 - 减去查询 - 错误 SQL0206N
- azure - 设备登录后 kubectl 返回错误 您必须登录到服务器(未经授权)
- angular - 模块在 Angular 中没有导出成员“CanActivate”
- r - 在 R 中使用 For 循环向表达式添加两个下标
- python - KeyError:Spyder 中的“pdb_use_exclamation_mark”
- python - uWSGI - 监听监听队列中打开的连接列表