Laravel 关系';与模型属性类似的模型的

Laravel 关系';与模型属性类似的模型的,laravel,eloquent,laravel-relations,laravel-models,Laravel,Eloquent,Laravel Relations,Laravel Models,我有一个航班的模型。 航班与支付日志有关系 在付款记录表中有两个字段:金额和类型(输入/输出或添加/订阅) 我想在航班模型上添加一个字段,例如总金额 航班模型上的总金额将是根据关系计算的字段 type amount I 5.0 I 10.0 O 2 Total_amount = I+I-O = 13 最佳做法是什么 在您的航班模型上创建一个方法,对日志表中的金额列求和: public function getTotalAmountAttribute()

我有一个
航班的模型。
航班
支付日志
有关系

付款记录
表中有两个字段:
金额
类型(输入/输出或添加/订阅)

我想在
航班
模型上添加一个字段,例如
总金额

航班
模型上的
总金额
将是根据
关系
计算的字段

type   amount
I       5.0
I       10.0
O       2

Total_amount = I+I-O = 13
最佳做法是什么

在您的
航班
模型上创建一个方法,对日志表中的
金额
列求和:

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;

谢谢,那么$this->payableLogs()和$this->payableLogs()之间有什么区别呢?
$this->paymentsLog
返回相关的
付款记录的集合(就像它执行查询一样),其中
$this->payableLogs()
返回查询生成器实例。当我们使用find(id)进行选择时,是否有办法在模型集合上查看此字段?是的,将此属性添加到您的
航班
类:
受保护的$appends=['total_amount']。这将确保它包含在每个飞行记录中。