1

我有一个模型Flights。与Flight有关系payments_log

表中payments_log有两个字段:amounttype(Input/Output or add/sub)

例如,我想在Flight模型上添加一个字段Total_amount

total_amount模型上的将Flight是一个从 计算的字段relationship

type   amount
I       5.0
I       10.0
O       2

Total_amount = I+I-O = 13

最佳做法是什么?

4

1 回答 1

2

在模型上创建一个访问器方法,对日志表中的列Flight求和:amount

public function getTotalAmountAttribute()
{
    // Sum log records of type I (add) 
    // and substract the sum of all log records of type ) (sub)
    return $this->paymentsLog()->where('type', 'I')->sum('amount') - $this->paymentsLog()->where('type', 'O')->sum('amount');
}

然后您可以使用以下方式访问它:

$flight->total_amount;
于 2020-04-11T15:46:54.743 回答