将父模型的数据提取到static :: saving()引导函数中

时间:2019-04-23 08:07:05

标签: laravel eloquent computed-values

我想使用父模型中的数据在子模型中运行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;
        }); 
    }
}

如何在此函数中获取“金额”和“利息”?

1 个答案:

答案 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');
}