用别名格式化where子句的正确方法-laravel

hgc7kmma  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(367)

我被困在一个问题上,我不太确定如何正确地重新格式化。以下是控制器功能的相关部分:

$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')

什么是正确的方法来获得所有这些数据的和(或零(0)) amountpayments_distributions 记录ID相同的表?
我一直在四处寻找,找不到一个合适的例子,我正在寻找什么,但肯定它更可能是搜索词或短语。谢谢。

w41d8nur

w41d8nur1#

在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

相关问题