【问题标题】:Laravel computed field on the relation's of a model like a model attributeLaravel 模型关系上的计算字段,如模型属性
【发布时间】:2020-07-24 08:00:08
【问题描述】:

我有一个Flights 的模型。 Flightpayments_log有关系。

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

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

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

type   amount
I       5.0
I       10.0
O       2

Total_amount = I+I-O = 13

最佳做法是什么?

【问题讨论】:

    标签: laravel eloquent laravel-relations laravel-models


    【解决方案1】:

    在您的 Flight 模型上创建一个 accessor 方法,对日志表中的 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;
    

    【讨论】:

    • 谢谢,$this->payableLogs() 和 $this->payableLogs 有什么区别?
    • $this->paymentsLog 返回相关payments_log 记录的集合(因为它执行查询),其中$this->payableLogs() 返回查询构建器实例。
    • 当我们用 find(id) 选择时,有什么办法可以在模型集合上看到这个字段?
    • 是的,将此属性添加到您的Flight 类:protected $appends = ['total_amount'];。这将确保它包含在每个飞行记录中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2019-05-16
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多