我有下一个问题 - 我有一个表invoices
和一个表receipts
。发票是由代理商创建的,我希望得到每个代理商的销售情况,但数字是错误的。
以下是我尝试的内容:
$agents = Agent::get();
$invoices_receipts_agent = array();
foreach ($agents as $agent) {
$payment_invoice = 0;
$payment_recepit = 0;
$id_agent = $agent->id_agent;
$invoices = Invoice::whereAgent_id($id_agent)->get();
foreach ($invoices as $invoice) {
$payment_invoice = $payment_invoice + $invoice->total_pay;
$recepits = Recepit::whereInvoice_id($invoice->id_invoice)->get();
if (count($recepits) > 0) {
foreach ($recepits as $recepit) {
$payment_recepit = $payment_recepit + $recepit->amount_payd;
}
}
}
$total = $payment_invoice - $payment_recepit;
$total_agents = ['name' => $agent->name, 'total' => $total];
array_push($invoices_receipts_agent, $total_agents);
}
我做了一个测试并为ID为5的代理创建了两张发票
First invoice: 10
Second invoice : 20
Total invoices: 30
然后我为第二张发票做了一个收件人,找到了预期的总额:
Total: 10 + 20 - 20 = 10 (correct total)
这太棒了,但是我有一个代理人有3600张发票,总有一些错误。总数(总数=发票 - 收据)太大了,但我无法弄清楚原因。
额外细节:数字的字段为float
。
答案 0 :(得分:0)
首先,您可以使用Eloquent Relationships更轻松地处理此问题。 在这种情况下,可以将代理和发票之间的一对多关系定义为:
class Agent {
...
function invoices(){
return $this->hasMany('App-Namespace\Invoice')
}
}
...并在Invoice上定义反向关系。 然后,您必须在Invoice和Receipt模型之间执行相同操作,因为Invoice可以包含一个到多个收据。 因此,如果Agents表主键是id,您可以说:
$agent = Agent::find($agent_id)->invoices->get();
...获取代理发票;或者:
$invoice = Invoice::find($invoice_id)->receipts->get();
...获取特定发票的所有收据。
最后实现你的代码:
$agents = Agent::all();
$invoices_receipts_agent = array();
foreach ($agents as $agent) {
$payment_invoice = 0;
$invoices = $agent->invoices->get();
foreach ($invoices as $invoice){
$payment_invoice += $invoice->total_pay;
$payment_receipt += $invoice->receipts->sum('amount_paid');
}
$total = $payment_invoice + $payment_receipt;
$invoices_receipts_agent[] = ['name' => $agent->name, 'total' => $total];
}
注意:我使用了 sum 收集功能来获取特定收据的 amount_paid 列的值的总和。您可以这样做以获得发票的total_pay列的总和,如:
$total_paid = $agent->invoices()->sum('total_pay');
答案 1 :(得分:0)
您能否确认当前版本的代码?
我看到了一些错字:
$recepits = Recepit::whereInvoice_id($invoice->id_invoice)->get();
if (count($receipts) > 0) {
我们遇到了问题:
如果这是您的最终代码,那些肯定是错误的,这会影响您的结果。