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

how does laravel handle multivalued attributes in table?

我意识到我的 "loan" table 上的 "interest_amount" 是多值属性。那么我应该创建一个 table 来拆分 "loan" table 还是应该创建一个不同的模型? "interest" 我需要不同的 table,因为我必须将每个月的利息标记为 paid/unpaid。

我创建了一个新模型 "InterestAmount" 和 table "interest_amounts" 一旦插入 "loan" 就必须自动插入。

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

此处 interest_amount 是使用 'amount' 计算的值,并且 'interest'。 table interestamount 中的数据必须自动插入。

自动进入需要使用事件和监听器吗??

在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 = 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,
]);