在 laravel 中的 table 中插入计算数据

insert computed data in table in laravel

我需要存储使用 get_Attribute 函数计算的 interest_amount 但是现在我需要将它插入 table.

我已经使用 static::saving 函数来计算 interest_amount 我不知道如何在控制器 $data 中调用它

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';

    public function getInterestAmountAttribute()
    {
        return ($this->amount)/100 * $this->interest;
    }

    public function member()
    {
        return $this->belongsTo(Member::class,'member_id','id');
    }

    protected static function boot() 
    {
        parent::boot();

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

LoanController.php

$data['amount'] = $request->amount;
$data['interest'] = $request->interest;
$data['interest_amount'] = $interest_amount;
$data['duration'] = $request->duration;
$data['status']= $request->status;
$data['member_id'] = $request->name;
$data['loan_type_id']= $request->loan_type;
$data['interest_type_id']= $request->interest_type;
$data['loan_payment_type_id']= $request->payment;

if(DB::table('loans')->insert($data)){
    return redirect()->route('loan')->with('success','data was successfuly inserted');
}

我最初没有 interest_amount 列,但我后来添加了它。我不知道如何使用我在控制器中使用的方法调用 saving 函数。

Model events 在您使用查询构建器将数据插入表中时不会触发。

你必须使用模型来保存数据,像这样:

如果您的模型属性是可批量分配的:

if((new Loan($data))->save()){
    return redirect()->route('loan')->with('success','data was successfuly inserted');
}

否则:

$loan = new Loan;
$loan->amount = $request->amount;
$loan->interest = $request->interest;
$loan->interest_amount = $interest_amount;
$loan->duration = $request->duration;
$loan->status = $request->status;
$loan->member_id = $request->name;
$loan->loan_type_id = $request->loan_type;
$loan->interest_type_id = $request->interest_type;
$loan->loan_payment_type_id = $request->payment;

if($loan->save()){
    return redirect()->route('loan')->with('success','data was successfuly inserted');
}