gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:05:46 24 4
gpt4 key购买 nike

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

id,customer_id,金额

我只想得到那些客户 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
}
}

Eloquent Join 有没有更好的方法?我怎样才能在 laravel 中变得 Eloquent ?

最佳答案

您是否在模型中设置了任何关系?一个更好的 Eloquent 查询将如下所示。您可能需要稍微调整一下

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();

关于php - 如何根据另外两个表的计算从一个表中检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55488177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com