在laravel的表中插入计算数据

时间:2019-04-17 08:18:08

标签: database laravel eloquent derived-column

我需要存储使用interest_amount函数计算的get_Attribute,但是现在我需要将其插入表中。

我已经使用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函数。

1 个答案:

答案 0 :(得分:1)

当您使用查询生成器将数据插入表中时,

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