我遇到了一个我不太确定如何正确重新格式化的问题。以下是控制器功能的相关部分:
$paidQuery = DB::table('shipments')
->leftJoin('customers', 'shipments.bill_to', '=', 'customers.id')
->leftJoin('customer_addresses', 'shipments.billerLocation', '=', 'customer_addresses.id')
->leftJoin('payments_distributions','shipments.id','=','payments_distributions.shipment_id')
->select('shipments.*', 'customers.customer_name','customer_addresses.billingMethod',DB::raw('COALESCE(sum(payments_distributions.amount),0) AS paid'));
$paidQuery->where('shipments.shipment_origin', 1);
$paidQuery->where('shipments.balance', '<', 'paid')
->where('shipments.balance','>', 0)
->whereNotIn('shipments.shipment_billing_status', [2,3,5]);
if(!empty($_GET['startDate']) || !empty($_GET['endDate'])){
$paidQuery->where(function($query) {
if(empty($_GET['startDate'])){
$startDate = Carbon::create(1900, 1, 1, 0, 0, 0);
} else {
$startDate = $_GET['startDate'];
}
if(empty($_GET['endDate'])){
$endDate = Carbon::now();
} else {
$endDate = $_GET['endDate'];
}
return $query->whereBetween('date', [$startDate, $endDate])
->orWhereNull('date');
});
}
$paidQuery->whereNull('shipments.deleted_at')
->orderBy('shipments.pro_number', 'DESC')
->groupBy('shipments.id')
->limit(100);
现在,如您在上面看到的,有一个select语句(第5行),最后是一个别名。这里仅作为如何返回我获取的数据的示例。我已经用它来验证什么是行和什么行不通,并且该特定行是否有效,该行不起作用的部分是此行:
$paidQuery->where('shipments.balance', '<', 'paid')
从记录ID相同的amount
表中获取所有payments_distributions
的和(或零(0))的正确方法是什么?
我一直在四处寻找,找不到合适的示例,但可以确定搜索词或措辞更有可能。 谢谢。
答案 0 :(得分:0)
在MySQL中,不可能在同一级别的where子句中使用select子句中定义的别名。但是,MySQL重载了HAVING
运算符以允许使用别名,因此以下内容应在此处起作用:
$paidQuery = DB::table('shipments')
->leftJoin('customers', 'shipments.bill_to', '=', 'customers.id')
->leftJoin('customer_addresses', 'shipments.billerLocation', '=', 'customer_addresses.id')
->leftJoin('payments_distributions','shipments.id','=','payments_distributions.shipment_id')
->select('shipments.*', 'customers.customer_name','customer_addresses.billingMethod',DB::raw('COALESCE(sum(payments_distributions.amount),0) AS paid'));
$paidQuery->where('shipments.shipment_origin', 1);
$paidQuery->having('shipments.balance', '<', 'paid');
$paidQuery->where('shipments.balance', '>', 0)
$paidQuery->whereNotIn('shipments.shipment_billing_status', [2,3,5]);
在这里要明确,我建议您使用以下原始MySQL:
HAVING paid > shipments.balance