Eloquent Model保存在DB中但在代码中找不到

时间:2018-01-01 20:14:15

标签: php eloquent

提前感谢您的帮助。我有一个发票模型,它与付款模式有一对多的关系,当我循环通过发票的付款以添加所有$ payment-> net并从$ invoice->成本中扣除它以查看剩下的余额。刚在同一个电话中进行的付款不会出现在$ invoice->付款中,感觉就像是缓存了一样。

Invoice.php

public function payments()
{
    return $this->hasMany('App\Payment');
}

public function net() :float
{
    $payments = $this->payments;

    $net = $this->cost;
    foreach ($payments as $payment) {
        $net += $payment->net;
    }

    return $net;
}

public function balance() :float
{
    return ($this->cost - $this->net());
}

Payment.php

public function invoice()
{
    return $this->belongsTo('App\Invoice');
}

PaymentController.php


    $invoice = Invoice::findOrFail($id);

    // Check ownership
    if(!$this->getCurrentUser()->isSuperuser() && $this->getCurrentUser()->id === $invoice->user_id) {
        throw new ModelNotFoundException();
    }

    $payment = new Payment($request->all());
    $payment->ref = Payment::generateRef($invoice->id, $request->input('type'));

    // Check for overpayment
    if($invoice->balance() < $payment->net) {
        throw new BadInputException('Payment exceeds balance.');
    }

    if($payment = $invoice->payments()->save($payment)) {
        if($invoice->balance() == 0) {
            $invoice->status = Invoice::CLOSED;
            $invoice->save();
        }
    }

    return $payment;

1 个答案:

答案 0 :(得分:0)

这不是我想要的解决方案,但我不想在这样的小问题上花费太多时间。我将尝试理解为什么模型稍后会缓存。

第一次运行$ invoice-&gt; balance()时,该值会被缓存,并且该功能不会考虑在评估新余额时所做的新付款。

所以下次我运行$ invoice-&gt; balance()我只需手动减去新的净付款。

 if($invoice->balance() - $payment->net == 0) {
     $invoice->status = Invoice::CLOSED;
     $invoice->save();
 }