我想使用父模型中的数据在子模型中运行saving()
函数
以前,我将计算数据插入到模型"Loan"中的表中,但现在我需要将其插入子模型" InterestAmount
贷款.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
protected static function boot()
{
parent::boot();
static::saving(function($model) {
$model->interest_amount = ($model->amount/100 )* $model->interest;
});
}
public function interest_amount()
{
return $this->hasMany(InterestAmount::class,'loan_id','id');
}
}
我想从贷款中删除储蓄功能.php并按如下方式使用。
兴趣.php
use IlluminateDatabaseEloquentModel;
class InterestAmount extends Model
{
public function loan()
{
$this->belongsTo(Loan::class,'loan_id','id');
}
protected static function boot()
{
parent::boot();
static::saving(function($model) {
$model->interest_amount = ($model->amount/100 )* $model->interest;
});
}
}
如何在此函数中获取"金额"和"利息"?
模型中InterestAmount
$model
变量是指一个InterestAmount
对象:
static::saving(function($model){
$model->interest_amount = ($model->loan->amount/100 )* $model->loan->interest;
});
然后,您需要使用关系方法获取相关loan
loan()
然后获取属性amount/interest
。
注意:正如@namelivia的评论所说,您缺少loan()
方法中的return
:
public function loan()
{
return $this->belongsTo(Loan::class,'loan_id','id');
}