laravel如何处理表中的多值属性?

问题描述 投票:0回答:1

我意识到我的“贷款”表上的“interest_amount”是多值属性。所以我应该创建一个表来分割“贷款”表或我应该创建一个不同的模型?我需要不同的表“兴趣”,因为我必须将每个月的利息标记为有偿/无偿。

我创建了一个新模型“InterestAmount”和表“interest_amounts”,一旦插入“贷款”,就必须自动插入。

Loan('id','amount','interest_rate')
InterestAmounts('id','loan_id','interest_amount')

这里interest_amount是使用'amount'和'interest'计算的值。并且必须自动插入表interestitount中的数据。

我是否需要使用事件和监听器进行自动输入?

laravel eloquent multivalue
1个回答
1
投票

在Laravel中,这可以通过使用一对多关系来解决。在这里,您的一笔贷款有多个InterestAmounts。

所以,你必须定义两个模型,

一个是Loan型号:

class Loan extends Model
{
  protected $table = 'Loan';

  public function interestAmounts()
  {
    return $this->hasMany(InterestAmount::class, 'loan_id');
  }
}

另一个是InterestAmount型号:

class InterestAmount extends()
{
  protected $table = 'InterestAmounts';

  public function loan()
  {
    return $this->belongsTo(Loan::class, 'loan_id');
  }
}

现在,如果您想在插入贷款并插入适当的计算时插入InterestAmounts,您可以执行以下操作:

贷款箱:

$loan = Loan::create([
  'amount' => $amountValue,
  'interest_rate => $interestRateValue,
]);

要通过适当的计算添加InterestAmounts

$loan->interestAmounts()->create([
  'interest_amount' => $loan->amount * $loan->intrest_rate,
]);

在这里,loan_id将自动添加。你甚至可以手动完成:

InterestAmount::crate([
  'loan_id' => $loan->id,
  'interest_amount' => $loan->amount * $loan->intrest_rate,
]);
© www.soinside.com 2019 - 2024. All rights reserved.