1

我想使用父模型中的数据来运行saving()子模型中的函数

以前,我在模型“Loan”中将计算数据插入到表中,但现在我需要将其插入到子模型“ InterestAmount”中

贷款.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 中删除保存功能并使用如下。

兴趣.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;
        }); 
    }
}

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

4

1 回答 1

1

模型内部的$model变量InterestAmount指的是一个InterestAmount对象:

static::saving(function($model){
    $model->interest_amount = ($model->loan->amount/100 )* $model->loan->interest;
}); 

然后您需要loan使用您的关系方法获取相关信息,loan()然后获取属性amount/interest

注意:正如@namelivia 的评论所说,您在方法中缺少returnloan()

public function loan()
{
    return $this->belongsTo(Loan::class,'loan_id','id');
}
于 2019-04-23T08:19:22.467 回答