Laravel - Sums,复杂关系和模型问题

时间:2018-03-27 17:00:15

标签: laravel laravel-5 model

我有一个客户索引表,我希望能够通过比较账单中的付款与其总金额来显示客户的当前余额,然后总结所有剩余金额。 / p>

目前我的客户模型看起来像这样(特别针对这个问题):

public function billToShipments()
{
    return $this->hasMany(Shipment::class, 'bill_to');
}

然后我的货件模型看起来像这样(与付款分配有关):

        public function paymentDistributions(){
    return $this->hasMany('App\Payments_Distribution', 'shipment_id','pro_number');
}

这些是与此特定问题相关的必要字段:

根据付款分配 -pro_number -amount(of distribution)

在货件下 -余额到期 -bill_to(这是客户ID)

我希望能够获得的所有balance_due账单的总和,其支付分配比客户应付的余额少。

例如,在货物中(假装在一个客户下):

SHIPMENT ID   |    Balance_Due
1234          |    10.00
1235          |    20.00
1236          |    30.00

并在payment_distributions表中:

PRO_NUMBER    |    AMOUNT
1234          |    2.00
1234          |    4.00
1235          |    20.00
1236          |    28.00

在客户身上,我想说他们有6.00美元的余额(因为10.00减去(2.00加4.00)等于4.00用于装运#1234,20.00美元完全支付装运#1235和剩余2.00用于装运#1236

同样,我想在客户表格中使用余额(在@foreach语句下)来提供资产负债表。

----更新了Jonas ----

这是我在客户的一个记录视图中获取剩余总和的时刻,我将以下内容传递给控制器​​的视图:

$invoicesOpen = Shipment
        ::whereRaw('balance > (SELECT IFNULL(SUM(payments_distributions.amount),0) FROM payments_distributions WHERE payments_distributions.shipment_id = pro_number)')
        ->where('bill_to','=',$customer->id)
        ->whereNotIn('shipment_billing_status', [2,3])
        ->orderBy('created_at','desc')->get();

此时我可以看到客户剩余1172.60美元,但通过Jonas'建议,我不知何故得到 - $ 5477.90

现在我可以获得一个已关闭的发票总额,目前为5240.30美元。最后一个数字仅用于表明我不确定Jonas'总计算。

1 个答案:

答案 0 :(得分:1)

将此添加到您的Customer型号:

public function getBalanceAttribute() {
    $toPay = $this->sum($this->billToShipments->pluck('balance_due'));
    $payments = $this->billToShipments->pluck('paymentDistributions')->collapse();
    $paid = $this->sum($payments->pluck('amount'));
    return bcsub($toPay, $paid, 2);
}

protected function sum($values) {
    return $values->reduce(function($carry, $item) {
        return bcadd($carry, $item, 2);
    }, '0');
}

然后像这样使用它:

$customers = Customer::with('billToShipments.paymentDistributions')->get();
foreach($customers as $customer) {
    // $customer->balance
}
相关问题