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