Laravel 5 分页时计算相关模型的列
我有一个名为Laravel 5 分页时计算相关模型的列,laravel-5,Laravel 5,我有一个名为Invoice的模型,它与hasMany和InvoiceItems有关。在InvoiceItems中有一个名为total的字段/列。处理分页时如何计算该字段?这是密码 $periode = $months_translate[date('n') - 1].'-'.date('Y'); $invoices = Invoice::where('billing_period', $periode) ->orderBy('number')->paginate($per_page
Invoice
的模型,它与hasMany
和InvoiceItems
有关。在InvoiceItems
中有一个名为total
的字段/列。处理分页时如何计算该字段?这是密码
$periode = $months_translate[date('n') - 1].'-'.date('Y');
$invoices = Invoice::where('billing_period', $periode)
->orderBy('number')->paginate($per_page);
$total_amount = 0; // this is what i am trying to figure out.
foreach($invoices as $invoice){
foreach($invoice->items as $item){
$total_amount += $item->sum('total');
}
}
$total\u amount
正在计算所有记录,包括当前计费周期之外的记录,因此它给出的结果是错误的。在编写查询时,您需要使用laravel with方法。它将获得满足您给定条件的发票的发票项。
读这个
我已经按照你的建议做了,但是结果仍然是错误的。@DarielPratama你有很多函数名InvoiceItems吗?还是仅仅是物品?在这种情况下,需要将关系的函数名作为参数传递给with方法。
$invoices = Invoice::with('InvoiceItems')->where('billing_period', $periode)
->orderBy('number')->paginate($per_page);