如何根据另外两个表的计算结果从一个表中检索数据?

时间:2019-04-03 06:09:33

标签: php mysql sql database laravel

假设我有三个分别名为Customer ,InvoicePayment的模型。 发票和付款模型看起来像

id , customer_id, amount

我只想吸引那些其     Invoice.sum(amount)>Payment.sum(amount)具有这些金额差异

我目前正在检索

$customers=Customer::get();
foreach($customers as $customer)
{  
  $pay=Payment::where('customer_id',$customer->id)->sum('amount');
  $due=Invoice::where('customer_id',$customer->id)->sum('amount');
  if($due>$pay){
   // showing this customers 
   }
}

是否有更好的口才加入方式? 如何获得雄辩的雄辩?

2 个答案:

答案 0 :(得分:2)

您是否在模型中设置了任何关系?更好的口才查询看起来像这样。您可能需要调整一下

Customer::join('payment','customer.id','=','payment.customer_id')
          ->join('invoice','customer.id','=','invoice.customer_id')
          ->select(array('customer.*'),DB::raw("SUM(payment.amount) as payment_sum,SUM(invoice.amount) as invoice_sum"))
          //->where('customer_id',$customer->id)
          ->groupBy('customer.id')  //replace with anything that make sense for you.
          ->havingRaw('invoice_sum > payment_sum')
          ->get();

答案 1 :(得分:1)

尝试一下

首先,在您的Customer模型中定义关系

public function payments()
{
  return $this->hasMany(Payment::class); //based on your logic or structure
}

public function invoices()
{
  return $this->hasMany(Invoice::class); //based on your logic or structure
}
Customer::with(['payments' => function($query) {
               $query->sum('amount');
         }])
        ->get();

$customers=Customer::with('payments','invoices')->get();
foreach($customers as $customer)
{  
  $pay = $customer->payments()->sum('amount');
  $due = $customer->invoices()->sum('amount');

   //other logic
}