如何在Laravel上使用口才来执行多表选择

时间:2020-09-22 08:44:02

标签: php mysql laravel eloquent query-builder

我有以下情况:

1-一张发票可以包含许多物品(商品或服务),每种商品或服务都以自己的价格出售。 (Invoice_items表)。在这种情况下,如果我们想知道发票的总金额,则可以对与之关联的项目的总金额进行求和。

2-可以通过许多收据来支付发票。因此,如果我们想知道发票是否已全部支付,我们将在每个receipment_item上支付的金额相加。

有关该场景的更多详细信息,请查看附图。

我想要两个雄辩的查询或类似的东西,可以帮助我: ry

  1. 检索所有未支付的发票。
  2. 从查询中检查是否已支付一张发票。

请考虑在我的发票模型中,我有:


public function invoiceItems()
    {
        return $this->hasMany(InvoiceItem::class, 'invoices_id');
    }


 public function payments()
    {
        return $this->hasMany(Payment::class, 'invoices_id');
    }

1 个答案:

答案 0 :(得分:0)

您可以append an attribute进入发票模型,例如:

$appends = ['is_paid'];

此属性需要访问器(请阅读有关访问器的文档):

public function getIsPaidAttribute () {
    // here you can make the calculation and return a true/false value
}

现在,在您的控制器中,您可以使用invoice.is_paid属性获取发票并进行过滤。

// retrieve all invoices
// you might need to add where conditions to lighten up 
// the results if you have thousands of records
$invoices = Invoice::all();

// filter paid invoices
$paidInvoices = $invoices->filter(function($i){
     return $i->is_paid === true;
});

最后,如果您想知道是否已支付发票,只需索要$invoice->is_paid