dongxia026531 2018-01-01 20:14
浏览 23

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

Thanks in advance for any help. I have an Invoice Model which has a one-to-many relationship with the payment model and when I loop through an invoice's payments to add all the $payment->net and subtract it from the $invoice->cost to see the balance that is left. The payment that was just made in the same call doesn't appear in $invoice->payments, it feels like its cached.

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条回答 默认 最新

  • dsgdhtr_43654 2018-01-02 00:42
    关注

    This is not the solution I was looking for but I don't like to expend too much time in little problems like this. I'll try to understand why is the model caching later.

    The first time I run $invoice->balance() the value gets cached and the function won't take into consideration the new payment made when evaluating the new balance.

    so the next time I ran $invoice->balance() i just manually subtract the new net payment.

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

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集